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:
Help: Shifting to ubuntu and opensource from Microsoft stack
I love SO and have been using it for the last 2 years. I've never posted any questions on it (because I found most answers though SO's search).
I have high hopes for this question.
I have been a .NET developer for the last 7-8 years (ASP.NET, ASP.NET MVC etc) and now i want to learn something new, especially outside Windows/Microsoft.
I have set aside 15 days where I am ready to give 4-5 hours daily.
Target is managing an Ubuntu VPS and hosting one self build website on any opensource stack (python or ruby).
Now I need help from all the open source community to get into their world.
Please help me.
A:
It's pretty brief, but this is what I'd do:
Install Ubuntu on my desktop machines, netbooks and laptops and play for a day.
Read about the philosophy of open-source, what it's all about (it's not just free).
Do a Python tutorial.
Choose a webserver technology, the most popular one is probably Apache.
Turn some local machines into webservers, and begin creating small pages in Python.
Read up on a complete Web framework like Django (if that's your thing).
Begin writing and testing a site on local machines.
Read up on SSH, and perform the configuration required on your VPN.
Transfer a stable snapshot of your website to the VPN and test.
Repeat steps 7 to 9 until 15 days is over.
Never go back to Windows, Microsoft, or any other barfware again.
A:
Your 'question' is quite vague, but from what I can understand you want us to suggest what stack you should look at in moving away from Microsoft technologies? While this is quite subjective (everyone likes technologies for their own reason) I can give you my own recommendation.
Personally, I am a web developer (well, most of the stuff I do is web development), and I originally started off with ASP.NET WebForms and so on. I started looking at ASP.NET MVC when it came out but then decided to give Ruby on Rails a go and pretty much never looked back.
There is a big difference in moving from Microsoft tools to other tools - if you rely a lot on autocomplete then you might be a bit disappointed with the tooling for the more dynamic languages - however there are a lot of good references available both online and for offline consumption.
One thing you might want to consider is checking out the PeepCode screen casts for both Ruby on Rails (their Rails stuff is a bit behind now that Rails 3 is out, but they are catching up) and also Node.js which is becoming popular in some camps.
There are also a number of tutorials available for this stuff too: http://railsnotes.com/rails-3/
My main recommendation though is to be comfortable with the core language (Ruby) and its idioms, before you try to understand the framework. You might love the framework but dislike the language which will just work against you.
Anyway, this is just my opinion - the main recommendation is to not worry too much about the best tools etc to use first, just try a language and if it doesn't work with you, move on to another one.
Good luck!
A:
There are a lot of different ways to do this depending on what you'd like to accomplish. This is what I'd suggest.
Set up an Ubuntu server. If you have a trash machine available, download an ISO for Ubuntu, and install it on that machine. The advantage of doing this is that you don't have to pay $10/month while you're figuring out what you want to do. Alternatively, you can go to Rackspace and get a small server set up for around $10/month, but I'd save that for when you're ready to deploy.
Install Django and MySql, or Ruby on Rails and MySql, and start doing the tutorials. I've used both, and they're both great. I'm more of a Python guy than a Ruby personally, so I prefer Django, but both Rails and Django are highly approachable with excellent tutorials.
Seriously, anything you want to do, there are tremendous resources to help you do it online. The single hardest part is jumping in and doing it and getting started. It's easier than you might think-- with ubuntu it's just a single command to get a working mysql installation going (sudo apt-get install mysql). Everything you need to know is just a Google search away. So the most important thing is to get over the initial hurdle and dive in.
So download Ubuntu (10.04 or 10.10, either one), install it, and get going!
A:
I think your transition will have two-parts:
Get used to running GNU/Linux, or another free software OS, as a user. Even though I'm not a professional programmer myself, I'll allow myself to imagine how hard it must be to change OS and frameworks when you're used to doing something one way all day long for many years. Don't underestimate this! Make sure to spend some time getting comfortable with your OS as a user -- having an extra layer of unfamiliarity will probably only upset and annoy you.
The actual developer stuff.
I'll focus on point 1, since others have already answered 2 well. Some unordered thoughts follow.
Make sure that you recognize that 1. will take time. You didn't become a Windows poweruser in a few weeks or even months, did you? As has been mentioned by others, a nice way to save time while doing this is starting to use the OS as your day-to-day one. Don't keep it far away on a VPS! Use it for browsing SO, use it for sending e-mail, use it for learning. Only then is it natural to start using it for developing. There is nothing like actually having a real problem to learn the tools neccessary to fix said problem. I'm sure you know this very well from your job :-)
Get acquainted with the differences of philosophy between Windows and your new OS. I'll mention two examples worth investigating and learning more about right away: 1: In GNU/Linux, a central package manager usually handles (almost) all of the software on your system. It takes care of updates and security fixes, and make sure you don't get a system full of cruft. For Debian/Ubuntu, the system is called apt, and there's tonnes you can read about it. 2: With such a nice package manager in place, shared libraries and dependencies in general can be handled properly -- there is no need for every piece of software to drag along with it everything it needs. Yes, disk space is cheap, but the Linux/BSD way is certainly a more æsthetically pleasing way of doing things.
As a developer, you probably have at least some interest in the general workings of the system, so get more than rudamentary familiarity with how your new OS works. I'm not talking about code-level stuff here, I'm talking about how it all "hangs together". For a developer such as yourself, a nice introduction could probably be had by trying to package a piece of software for your distro of choice (for Debian/Ubuntu, there is a nice guide).
To sum it all up: Take it slowly, and recognize that you didn't learn to be efficient in your current setting overnight. Treat it all like learning a very unrelated foreign language.
As for the actual developer stuff, point 2, you'll certainly discover that Python (and probably Ruby, which I'm not familiar with) feels much more at home in your new OS than in your old.
Edit: Another point I might add is that you should use the fact that you're a programmer in two ways. Firstly, when asking for help from other free software users, you'll tend to feel much more welcome if your question can be phrased in a technically accurate manner. Secondly, use the source, Luke; although it's not always a practical solution, don't forget that having the source code freely available and modifiable can be a real advantage for someone who's a good programmer.
A:
First of all, I think that you need to take this a bit slower - you are talking about not just a new language and framework, but a completely new stack with a different way of thinking. Basic tools and assumptions are quite different between the Open Source and MS worlds.
Whichever Open Source stack you use, it is going to take some time and a couple of projects for you to fully adjust. There may be points where your existing experience might actually cause you a bit of frustration, because something that looks similar to what you already know will not follow your expectations.
Perhaps treat your first project as a trial run and don't worry about testing or deployment - just go through a screencast or tutorial and use SQLite so that you don't have to think about the database server. This will give you an overview of the platform.
If possible work with someone else for your second project, or find an appropriate mailing list, forum or IRC channel and don't hesitate to ask questions if you find that there's something you are struggling with.
The tools for deployment and maintenance are great but these areas tends to much less well-covered by books and blogs, so don't be surprised if you need a little help when you reach that point.
| Help: Shifting to ubuntu and opensource from Microsoft stack | I love SO and have been using it for the last 2 years. I've never posted any questions on it (because I found most answers though SO's search).
I have high hopes for this question.
I have been a .NET developer for the last 7-8 years (ASP.NET, ASP.NET MVC etc) and now i want to learn something new, especially outside Windows/Microsoft.
I have set aside 15 days where I am ready to give 4-5 hours daily.
Target is managing an Ubuntu VPS and hosting one self build website on any opensource stack (python or ruby).
Now I need help from all the open source community to get into their world.
Please help me.
| [
"It's pretty brief, but this is what I'd do:\n\nInstall Ubuntu on my desktop machines, netbooks and laptops and play for a day.\nRead about the philosophy of open-source, what it's all about (it's not just free).\nDo a Python tutorial.\nChoose a webserver technology, the most popular one is probably Apache.\nTurn s... | [
3,
2,
1,
1,
0
] | [] | [] | [
".net",
"open_source",
"python",
"ruby",
"ubuntu"
] | stackoverflow_0003899285_.net_open_source_python_ruby_ubuntu.txt |
Q:
Django's Model fields are defined on the class level?
Maybe my question is little childish. A django model is typically defined like this:
class DummyModel(models.Model):
field1 = models.CharField()
field2 = models.CharField()
As per my understanding, field1 and field2 are defined on the class level instead of instance level. So different instances will share the same field value. How can this be possible considering a web application should be thread safe? Am I missing something in my python learning curve?
A:
You are correct that normally attributes declared at the class level will be shared between instances. However, Django uses some clever code involving metaclasses to allow each instance to have different values. If you're interested in how this is possible, Marty Alchin's book Pro Django has a good explanation - or you could just read the code.
A:
Think of the models you define as specifications. You specify the fields that you want, and when Django hands you back an instance, it has used your specifications to build you an entirely different object that looks the same.
For instance,
field1 = models.CharField()
When you assign a value to field1, such as 'I am a field', don't you think it's strange that you can assign a string to a field that is supposed to be a 'CharField'? But when you save that instance, everything still works?
Django looks at the CharField, says "this should be a string", and hands it off to you. When you save it, Django checks the value against the specification you've given, and saves it if it's valid.
This is a very simplistic view of course, but it should highlight the difference between defining a model, and the actual instance you get to work with.
| Django's Model fields are defined on the class level? | Maybe my question is little childish. A django model is typically defined like this:
class DummyModel(models.Model):
field1 = models.CharField()
field2 = models.CharField()
As per my understanding, field1 and field2 are defined on the class level instead of instance level. So different instances will share the same field value. How can this be possible considering a web application should be thread safe? Am I missing something in my python learning curve?
| [
"You are correct that normally attributes declared at the class level will be shared between instances. However, Django uses some clever code involving metaclasses to allow each instance to have different values. If you're interested in how this is possible, Marty Alchin's book Pro Django has a good explanation - o... | [
2,
0
] | [] | [] | [
"django",
"field",
"model",
"python"
] | stackoverflow_0003897033_django_field_model_python.txt |
Q:
How do I dump the TCP client's buffer in order to accept more data?
I've got a simple TCP server and client. The client receives data:
received = sock.recv(1024)
It seems trivial, but I can't figure out how to recieve data larger than the buffer. I tried chunking my data and sending it multiple times from the server (worked for UDP), but it just told me that my pipe was broken.
Suggestions?
A:
If you have no idea how much data is going to pour over the socket, and you simply want to read everything until the socket closes, then you need to put socket.recv() in a loop:
# Assumes a blocking socket.
while True:
data = sock.recv(4096)
if not data:
break
# Do something with `data` here.
A:
Mike's answer is the one you're looking for, but that's not a situation you want to find yourself in. You should develop an over-the-wire protocol that uses a fixed-length field that describes how much data is going to be sent. It's a Type-Length-Value protocol, which you'll find again and again and again in network protocols. It future-proofs your protocol against unforeseen requirements and helps isolate network transmission problems from programmatic ones.
The sending side becomes something like:
socket.write(struct.pack("B", type) #send a one-byte msg type
socket.write(struct.pack("H", len(data)) #send a two-byte size field
socket.write(data)
And the receiving side something like:
type = socket.read(1) # get the type of msg
dataToRead = struct.unpack("H", socket.read(2))[0] # get the len of the msg
data = socket.read(dataToRead) # read the msg
if TYPE_FOO == type:
handleFoo(data)
elif TYPE_BAR == type:
handleBar(data)
else:
raise UnknownTypeException(type)
You end up with an over-the-wire message format that looks like:
struct {
unsigned char type;
unsigned short length;
void *data;
}
A:
Keep in mind that:
Your operating system has it's own idea of what it's TCP/IP socket buffer size is.
TCP/IP packet maximum size (generally is 1500 bytes)
pydoc for socket suggests that 4096 is a good buffer size
With that said, it'd really be helpful to see the code around that one line. There are a few things that could play into this, if you're using select or just polling, is the socket non-blocking, etc.
It also matters how you're sending the data, if your remote end disconnects. More details.
| How do I dump the TCP client's buffer in order to accept more data? | I've got a simple TCP server and client. The client receives data:
received = sock.recv(1024)
It seems trivial, but I can't figure out how to recieve data larger than the buffer. I tried chunking my data and sending it multiple times from the server (worked for UDP), but it just told me that my pipe was broken.
Suggestions?
| [
"If you have no idea how much data is going to pour over the socket, and you simply want to read everything until the socket closes, then you need to put socket.recv() in a loop:\n# Assumes a blocking socket.\nwhile True:\n data = sock.recv(4096)\n if not data:\n break\n # Do something with `data` h... | [
1,
1,
0
] | [] | [] | [
"python",
"tcp"
] | stackoverflow_0003902757_python_tcp.txt |
Q:
web access by python
i'am looking up for way to enter web site "Login"
i tried this
login_form_seq = [
('user', 'Lick'),
('pass', 'Shot'),
('submit', 'login')]
A=urllib.urlencode(login_form_seq)
opener = urllib2.build_opener()
try:
site = opener.open('http://www.SMS-Example.com/user.php', A).read()
site2 = urllib.urlopen('http://www.SMS-Example.com/sms.php').read()
print site2
except(urllib2.URLError), msg:
print msg
site = ""
pass
but actually what I should put on submit and login? i put it randomly !!
thanks...
A:
It will depend from site to site and on many site you won't even need a submit value, user/pass should be sufficient and then in many other sites they may have some hidden fields in the login form, so best way is to see the fields in the form you are submitting either directly in html or using some tool like firebug.
Other thing you must know is that logging thru one http request doesn't enable login for next http request, for that you will need to track cookies, which is not very easy but not very difficult task.
Instead you can just use twill or mechanize
A:
Really depends. Usually programmers discards value of a submit button, setting its value to something meaningful, but it isn't set in stone. In your case 'login' is the name of a button control, 'login' is its value and it will be the button's label and would be discarded with 99% probability.
| web access by python | i'am looking up for way to enter web site "Login"
i tried this
login_form_seq = [
('user', 'Lick'),
('pass', 'Shot'),
('submit', 'login')]
A=urllib.urlencode(login_form_seq)
opener = urllib2.build_opener()
try:
site = opener.open('http://www.SMS-Example.com/user.php', A).read()
site2 = urllib.urlopen('http://www.SMS-Example.com/sms.php').read()
print site2
except(urllib2.URLError), msg:
print msg
site = ""
pass
but actually what I should put on submit and login? i put it randomly !!
thanks...
| [
"It will depend from site to site and on many site you won't even need a submit value, user/pass should be sufficient and then in many other sites they may have some hidden fields in the login form, so best way is to see the fields in the form you are submitting either directly in html or using some tool like fireb... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003905817_python.txt |
Q:
Why can't I call read() twice on an open file?
For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?
Here's the code
f = f.open()
# get the year
match = re.search(r'Popularity in (\d+)', f.read())
if match:
print match.group(1)
# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', f.read())
if matches:
# matches is always None
Of course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call read() twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?
A:
Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.
To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.
Ps. Don't forget to close the file after you are done with it.
A:
As other answers suggested, you should use seek().
I'll just write an example:
>>> a = open('file.txt')
>>> a.read()
#output
>>> a.seek(0)
>>> a.read()
#same output
A:
Everyone who has answered this question so far is absolutely right - read() moves through the file, so after you've called it, you can't call it again.
What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:
f = f.open()
text = f.read() # read the file into a local variable
# get the year
match = re.search(r'Popularity in (\d+)', text)
if match:
print match.group(1)
# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', text)
if matches:
# matches will now not always be None
A:
The read pointer moves to after the last read byte/character. Use the seek() method to rewind the read pointer to the beginning.
A:
Every open file has an associated position.
When you read() you read from that position.
For example read(10) reads the first 10 bytes from a newly opened file, then another read(10) reads the next 10 bytes.
read() without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call read() there is nothing to read.
You can use seek to move the file position. Or probably better in your case would be to do one read() and keep the result for both searches.
A:
read() consumes. So, you could reset the file, or seek to the start before re-reading. Or, if it suites your task, you can use read(n) to consume only n bytes.
| Why can't I call read() twice on an open file? | For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?
Here's the code
f = f.open()
# get the year
match = re.search(r'Popularity in (\d+)', f.read())
if match:
print match.group(1)
# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', f.read())
if matches:
# matches is always None
Of course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call read() twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?
| [
"Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.\nTo answer your question directly, onc... | [
186,
43,
22,
15,
3,
1
] | [
"I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can... | [
-1
] | [
"io",
"python"
] | stackoverflow_0003906137_io_python.txt |
Q:
How to control a frame from another frame?
I'm writing a small app which has 2 separate frames.
The first frame is like a video player controller. It has Play/Stop/Pause buttons etc. It's named controller.py.
The second frame contains OpenGL rendering and many things inside it, but everything is wrapped inside a Frame() class as the above. It's named model.py.
I'm up to the final part where I have to "join" these two together.
Does anyone know how to control a frame (model.py) from another frame (controller.py)?
I would like to do something like a movie player when you clicks play it pops up a new window and play until the stop button is clicked.
If you know how, please let me know. (Just tell me in general no need to specific).
A:
Theres not much too it, you create an instance of your model class in your controller and call its methods. So for example when you click the models stop button its handler calls the appropriate method of your model class to stop playback.
If you would like your frames to be decoupled somewhat, you could use pubsub, and simply setup some listeners in your model for messages from your controller.
Here's a tutorial I just found on communciating between two frames using pubsub, it's not exactly what you want to do, but it should be enough to get you started in the right direction if you decide to use pubsub.
A:
I'd definitely use PubSub as it's probably the cleanest way I can think of to do it. You can also do it with wx.PostEvent or use a modal frame.
| How to control a frame from another frame? | I'm writing a small app which has 2 separate frames.
The first frame is like a video player controller. It has Play/Stop/Pause buttons etc. It's named controller.py.
The second frame contains OpenGL rendering and many things inside it, but everything is wrapped inside a Frame() class as the above. It's named model.py.
I'm up to the final part where I have to "join" these two together.
Does anyone know how to control a frame (model.py) from another frame (controller.py)?
I would like to do something like a movie player when you clicks play it pops up a new window and play until the stop button is clicked.
If you know how, please let me know. (Just tell me in general no need to specific).
| [
"Theres not much too it, you create an instance of your model class in your controller and call its methods. So for example when you click the models stop button its handler calls the appropriate method of your model class to stop playback.\nIf you would like your frames to be decoupled somewhat, you could use pub... | [
4,
1
] | [] | [] | [
"frame",
"python",
"send",
"wxpython"
] | stackoverflow_0003898988_frame_python_send_wxpython.txt |
Q:
blender not responding to my accelerometer motion
m using arduino to interact the accelerometer MMA7361L with blender2.49.using python 2.62.
my arduino code is :
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(analogRead(0)/4, BYTE); //x-axis
Serial.print(analogRead(1)/4, BYTE); //y-axis
Serial.print(analogRead(2)/4, BYTE); //z-axis
delay(40);
}
my python code is:
import Blender
import GameLogic
import serial
serialport = serial.Serial('COM4', 9600)
ob = Blender.Object.Get ('Cube')
cont=GameLogic.getCurrentController()
own = cont.owner
rotxx = move.dRot[0]
rotyy = move.dRot[1]
rotzz = move.dRot[2]
move = cont.actuators["move"]
Blender.Window.WaitCursor(1)
x=[0,0,0]
for i in range(1, 100):
x1[0] = serialport.read(size=1)
x1[1] = serialport.read(size=1)
x1[2] = serialport.read(size=1)
x2=[(((m - n)*1.65)/180) for m,n in zip(x,x1)]
rotxx = rotxx + x2[0]
rotyy = rotyy + x2[1]
rotzz = rotzz + x2[2]
move.dRot=(rotxx,rotyy,rotzz)
cont.activate(move)
x1=x
else:
serialport.close()
Blender.Window.WaitCursor(0)
have made the sensor actuator connection.. no errors shown in implementation but blender cube shows no movement.
A:
In your python code, you only read the sensor values coming over a serial port 100 times, which is 4 seconds worth of sensor data at 40 ms per update (according to your processing code). You need to constantly read the sensor values and update scene orientation, so use a while loop like this:
read_sensors = True
while(read_sensors):
# call serialport.read() to read current sensor values
# update scene
Make sure that this can run at least every 40 milliseconds, since that's how often you're having arduino board write accelerometer values to the serial port. If you don't read data from the serial port often enough it will buffer, causing values appearing in serialport.read() to lag behind current accelerometer values that arduino board is reading. That won't look very interactive.
A:
I am not sure if you are incurring in the same problem I was when I made a python <-> arduino application, yet...
By default, when a serial connection is opened on the USB port, arduino will auto reset itself. Since the reboot it is not instant, your python programme will most likely complete its 100 times read cycle before arduino even starts writing.
If that is the problem you can either:
Insert time.sleep(3) (or whatever values works for you) after opening the serial connection.
Stick a 120 ohm resistor between RESET and 5V pins on your board, as described here (this will deactivate the auto-reset feature).
HTH!
| blender not responding to my accelerometer motion | m using arduino to interact the accelerometer MMA7361L with blender2.49.using python 2.62.
my arduino code is :
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(analogRead(0)/4, BYTE); //x-axis
Serial.print(analogRead(1)/4, BYTE); //y-axis
Serial.print(analogRead(2)/4, BYTE); //z-axis
delay(40);
}
my python code is:
import Blender
import GameLogic
import serial
serialport = serial.Serial('COM4', 9600)
ob = Blender.Object.Get ('Cube')
cont=GameLogic.getCurrentController()
own = cont.owner
rotxx = move.dRot[0]
rotyy = move.dRot[1]
rotzz = move.dRot[2]
move = cont.actuators["move"]
Blender.Window.WaitCursor(1)
x=[0,0,0]
for i in range(1, 100):
x1[0] = serialport.read(size=1)
x1[1] = serialport.read(size=1)
x1[2] = serialport.read(size=1)
x2=[(((m - n)*1.65)/180) for m,n in zip(x,x1)]
rotxx = rotxx + x2[0]
rotyy = rotyy + x2[1]
rotzz = rotzz + x2[2]
move.dRot=(rotxx,rotyy,rotzz)
cont.activate(move)
x1=x
else:
serialport.close()
Blender.Window.WaitCursor(0)
have made the sensor actuator connection.. no errors shown in implementation but blender cube shows no movement.
| [
"In your python code, you only read the sensor values coming over a serial port 100 times, which is 4 seconds worth of sensor data at 40 ms per update (according to your processing code). You need to constantly read the sensor values and update scene orientation, so use a while loop like this:\nread_sensors = True\... | [
1,
1
] | [] | [] | [
"arduino",
"blender",
"python"
] | stackoverflow_0003884425_arduino_blender_python.txt |
Q:
Python "strange" output
class Foo(object):
def __init__(self,x):
self.x = x
self.is_bar = False
def __repr__(self): return str(self.x)
class Bar(object):
def __init__(self,l = []):
self.l = l
def add(self,o):
self.l += [o]
def __repr__(self): return str(self.l)
def foo_plus_foo(f1,f2):
t = Bar()
if not (f1.is_bar and f2.is_bar):
f1.is_bar = True
f2.is_bar = True
t.add(f1)
t.add(f2)
print 'HERE'
return t
if __name__ == '__main__':
li = [Foo(1), Foo(2)]
print foo_plus_foo(li[0],li[1])
print foo_plus_foo(li[0],li[1])
UNEXPECTED OUTPUT:
HERE
[1, 2]
[1, 2]
EXPECTED OUTPUT:
HERE
[1, 2]
[]
What is happening? What did I do wrong? Why is python using old value? What do I do to avoid this?
Thanks!
A:
Never. Do. This.
def __init__(self,l = []):
Never.
One list object is reused. And it's Mutable, so that each time it's reused, the one and only [] created in your method definition is updated.
Always. Do. This.
def __init__( self, l= None ):
if l is None: l = []
That creates a fresh, new, unique list instance.
A:
You are defining l as having a default value of [].
This is a classic Python pitfall.
class Bar(object):
def __init__(self,l = []):
Default values are evaluated at definition time not run-time.
It is evaluated only once.
So t=Bar() sets t.l to the very same list every time.
To fix this, change Bar to
class Bar(object):
def __init__(self,l = None):
if l is None:
l=[]
self.l = l
def add(self,o):
self.l += [o]
def __repr__(self): return str(self.l)
A:
The culprit is the l=[] defined in the Bar class definition.
This list is instantiated once during class definition and is used as the default.
Super dangerous!! I and many others have been burned by this one, trust me the scarring is deep.
Problematic use of mutable.
class Bar(object):
def __init__(self,l = []):
self.l = l
def add(self,o):
self.l += [o]
def __repr__(self): return str(self.l)
Try using an immutable:
class Bar(object):
def __init__(self,l = None):
if l is None:
self.l = []
else:
self.l = l
def add(self,o):
self.l += [o]
def __repr__(self): return str(self.l)
A:
Others have explained the problem and suggested using l=None and an explicit test for it. I'd like to suggest a different approach:
class Bar(object):
def __init__(self, l=[]):
self.l = list(l)
# and so on...
This guarantees a new blank list each time by default, and also assures that if a caller passes in a list of their own, you get a copy of that list rather than a reference to the caller's list. As an added benefit, callers can pass in anything that the list constructor can consume, such as a tuple or a string, and your code doesn't have to worry about that; it can just deal with a list.
If you just save a reference to the list the caller gives you, and later change the list named self.l, you may be inadvertently changing the list that was passed in, too (since both your class and the caller now have a reference to the same object). Similarly, if they change the list after calling your constructor, your "copy" will be changed too (since it's not actually a copy). Of course, it could be that this is behavior you want, but probably not in this case.
Although if you never manipulate the list (i.e. add, replace, or delete items), but only refer to it or replace it wholesale, copying it is usually a waste of time and memory.
The copy made using the list() constructor is shallow. That is, the list itself is a new object, but if the original list contains references to mutable objects (such as other lists or dictionaries, or instances of most other classes), the same problem can arise if you change those objects, because they are still shared between the lists. This is an issue less frequently than you might think, but if it is, you can perform a deep copy using the deepcopy() function in the copy module.
| Python "strange" output | class Foo(object):
def __init__(self,x):
self.x = x
self.is_bar = False
def __repr__(self): return str(self.x)
class Bar(object):
def __init__(self,l = []):
self.l = l
def add(self,o):
self.l += [o]
def __repr__(self): return str(self.l)
def foo_plus_foo(f1,f2):
t = Bar()
if not (f1.is_bar and f2.is_bar):
f1.is_bar = True
f2.is_bar = True
t.add(f1)
t.add(f2)
print 'HERE'
return t
if __name__ == '__main__':
li = [Foo(1), Foo(2)]
print foo_plus_foo(li[0],li[1])
print foo_plus_foo(li[0],li[1])
UNEXPECTED OUTPUT:
HERE
[1, 2]
[1, 2]
EXPECTED OUTPUT:
HERE
[1, 2]
[]
What is happening? What did I do wrong? Why is python using old value? What do I do to avoid this?
Thanks!
| [
"Never. Do. This.\ndef __init__(self,l = []):\n\nNever.\nOne list object is reused. And it's Mutable, so that each time it's reused, the one and only [] created in your method definition is updated.\nAlways. Do. This.\ndef __init__( self, l= None ):\n if l is None: l = []\n\nThat creates a fresh, new, unique ... | [
5,
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003905448_python.txt |
Q:
Disable browser caching in pylons
I'm have an action /json that returns json from the server.
Unfortunately in IE, the browser likes to cache this json.
How can I make it so that this action doesn't cache?
A:
Make sure your response headers have:
Cache-Control: no-cache
Pragma: no-cache
Expires=-1
A:
Make sure your responses are not telling the browser that the content expires in the future. There are two HTTP headers the control this.
Expires
Cache-Control - There are many possible values for this header, but the one that controls expiration is max-age=foo.
In addition, IE may be revalidating. This means that IE includes some extra information in the request that tell the web server what version of the resource it has in its cache. If the browser's cached version is current, your server can respond with 304 Not Modified and NOT include the content in the responses. "Conditionatl GET requests" include this versioning information. It's possible that your server is giving 304 responses when it shouldn't be.
There are two sets of headers that control revalidation:
Last-Modified + If-Modified-Since
ETag + If-None-Match
Last-Modified, and ETag are response headers that tell the browser what the version of the resource it is about to receive. If you don't want browsers to revalidate, don't set these. If-Modified-Since and If-None-Match are the corresponding request headers that the browser uses to report the version of a stale resource that it needs to revalidate with the server.
There are various tools to see what HTTP headers your server is sending back to the browser. One is the Firefox extension Live HTTP Headers. Another tool, which Steve Sounders recommends is IBM Page Detailer. I haven't tried this one myself, but it doesn't depend on the browser that you're using.
A:
This is a common problem -- IE caches all ajax/json requests on the client side. Other browsers do not.
To work around it, generate a random number and append it to your request url as a variable. This fools IE into thinking it's a new request.
Here's an example in javascript, you can do something similar in Python:
function rand() {
return Math.floor(Math.random()*100000);
}
$("#content").load("/posts/view/1?rand="+rand());
A:
The jQuery library has pretty nice ajax functions, and settings to control them. One of them is is called "cache" and it will automatically append a random number to the query that essentially forces the browser to not cache the page. This can be set along with the parameter "dataType", which can be set to "json" to make the ajax request get json data. I've been using this in my code and haven't had a problem with IE.
Hope this helps
| Disable browser caching in pylons | I'm have an action /json that returns json from the server.
Unfortunately in IE, the browser likes to cache this json.
How can I make it so that this action doesn't cache?
| [
"Make sure your response headers have:\nCache-Control: no-cache\nPragma: no-cache\nExpires=-1\n\n",
"Make sure your responses are not telling the browser that the content expires in the future. There are two HTTP headers the control this.\n\nExpires\nCache-Control - There are many possible values for this header,... | [
3,
2,
1,
1
] | [] | [] | [
"caching",
"internet_explorer",
"pylons",
"python"
] | stackoverflow_0002439987_caching_internet_explorer_pylons_python.txt |
Q:
How to set up global connection to database?
I have problem with setting up database connection. I want to set connection, where I can see this connection in all my controllers.
Now I use something like this in my controller:
db = create_engine('mysql://root:password@localhost/python')
metadata = MetaData(db)
email_list = Table('email',metadata,autoload=True)
In development.ini I have:
sqlalchemy.url = mysql://root@password@localhost/python
sqlalchemy.pool_recycle = 3600
How do I set _____init_____.py?
A:
I hope you got pylons working; for anyone else that may later read question I'll present some pointers in the right direction.
First of all, you are only creating a engine and a metadata object. While you can use the engine to create connections directly you would almost always use a Session to manage querying and updating your database.
Pylons automatically setups this for you by creating a engine from your configuration file, then passing it to yourproject.model.__init__.py:init_model() which binds it to a scoped_session object.
This scoped_session object is available from yourproject.model.meta and is the object you would use to query your database. For example:
record = meta.Session.query(model.MyTable).filter(id=42)
Because it is a scoped_session it automatically creates a Session object and associates it with the current thread if it doesn't already exists. Scoped_session passes all action (.query(), .add(), .delete()) down into the real Session object and thus allows you a simple way to interact the database with having to manage the non-thread-safe Session object explicitly.
The scoped_session, Session, object from yourproject.model.meta is automatically associated with a metadata object created as either yourproject.model.meta:metadata (in pylons 0.9.7 and below) or yourproject.model.meta:Base.metadata (in pylons 1.0). Use this metadata object to define your tables. As you can see in newer versions of pylons a metadata is associated with a declarative_base() object named Base, which allows you to use SqlAlchemy's declarative style.
Using this from the controller
from yourproject import model
from yourproject.model import Session
class MyController(..):
def resource(self):
result = Session.query(model.email_list).\
filter(model.email_list.c.id=42).one()
return str(result)
Use real connections
If you really want to get a connection object simply use
from yourproject.model import Session
connection = Session.connection()
result = connection.execute("select 3+4;")
// more connection executions
Session.commit()
However this is all good, but what you should be doing is...
This leaves out that you are not really using SqlAlchemy much. The power of SqlAlchemy really shines when you start mapping your database tables to python classes. So anyone looking into using pylons with a database should take a serious look at what you can do with SqlAlchemy. If SqlAlchemy starts out intimidating simply start out with using its declarative approach, which should be enough for almost all pylons apps.
In your model instead of defining Table constructs, do this:
from sqlalchemy import Column, Integer, Unicode, ForeignKey
from sqlalchemy.orm import relation
from yourproject.model.meta import Base
class User(Base):
__tablename__ = 'users'
# primary_key implies nullable=False
id = Column(Integer, primary_key=True, index=True)
# nullable defaults to True
name = Column(Unicode, nullable=False)
notes = relation("UserNote", backref="user")
query = Session.query_property()
class UserNote(Base):
__tablename__ = 'usernotess'
# primary_key implies nullable=False
id = Column(Integer, primary_key=True, index=True)
userid = Column(Integer, index=True, ForeignKey("User.id"))
# nullable defaults to True
text = Column(Unicode, nullable=False)
query = Session.query_property()
Note the query objects. These are smart object that live on the class and associates your classes with the scoped_session(), Session. This allows you to event more easily extract data from your database.
from sqlalchemy.orm import eagerload
def resource(self):
user = User.query.filter(User.id==42).options(eagerload("notes")).one()
return "\n".join([ x.text for x in user.notes ])
A:
1.0 version of Pylons use declarative syntax. More about this, you can see here .
In mode/init.py you can write somthing like this:
from your_programm.model.meta import Session, Base
from sqlalchemy import *
from sqlalchemy.types import *
def init_model(engine):
Session.configure(bind=engine)
class Foo(Base) :
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
name = Column(String)
...
A:
What you want to do is modify the Globals class in your app_globals.py file to include a .engine (or whatever) attribute. Then, in your controllers, you use from pylons import app_globals and app_globals.engine to access the engine (or metadata, session, scoped_session, etc...).
| How to set up global connection to database? | I have problem with setting up database connection. I want to set connection, where I can see this connection in all my controllers.
Now I use something like this in my controller:
db = create_engine('mysql://root:password@localhost/python')
metadata = MetaData(db)
email_list = Table('email',metadata,autoload=True)
In development.ini I have:
sqlalchemy.url = mysql://root@password@localhost/python
sqlalchemy.pool_recycle = 3600
How do I set _____init_____.py?
| [
"I hope you got pylons working; for anyone else that may later read question I'll present some pointers in the right direction.\nFirst of all, you are only creating a engine and a metadata object. While you can use the engine to create connections directly you would almost always use a Session to manage querying an... | [
3,
2,
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002603093_pylons_python_sqlalchemy.txt |
Q:
Simplest way to calculate the width and height of a jpeg image in Python
How can I calculate the width and height of an image in Python?
I'm using the "Image" library already if that makes it easier.
Thanks.
A:
im=Image.open(pic)
print im.size
| Simplest way to calculate the width and height of a jpeg image in Python | How can I calculate the width and height of an image in Python?
I'm using the "Image" library already if that makes it easier.
Thanks.
| [
"im=Image.open(pic) \nprint im.size \n\n"
] | [
5
] | [] | [] | [
"image",
"image_processing",
"python"
] | stackoverflow_0003907360_image_image_processing_python.txt |
Q:
How can I implement a color table with VTK / TK in python
I'm developing an application in VTK / TK and I was wondering what's the best way to provide the user with a table which lists items and allow the user to pick the color for each item:
item1 | color
item2 | color
item3 | color
thanks
A:
I would create a frame, then write a loop that creates a label widget and a button for each item. The background of the button would be the current color. There needs not be any text on the button, just make it square. The button would call a method that calls tk_chooseColor to get a color from the user.
| How can I implement a color table with VTK / TK in python | I'm developing an application in VTK / TK and I was wondering what's the best way to provide the user with a table which lists items and allow the user to pick the color for each item:
item1 | color
item2 | color
item3 | color
thanks
| [
"I would create a frame, then write a loop that creates a label widget and a button for each item. The background of the button would be the current color. There needs not be any text on the button, just make it square. The button would call a method that calls tk_chooseColor to get a color from the user. \n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003907123_python_tkinter.txt |
Q:
Python - PIL - Missing images
Trying to use pil for creating grid-like layout from images. But that code only draws first column. Can anyone help me?
def draw(self):
image=Image.new("RGB",((IMAGE_SIZE[0]+40)*5+40,(IMAGE_SIZE[1]+20)*CHILD_COUNT+20),(255,255,255))
paste_x=(-1)*IMAGE_SIZE[0]
paste_y=(-1)*IMAGE_SIZE[1]
i=0
for a range(5):
paste_x=paste_x+IMAGE_SIZE[0]+40
j=0
for b in range(4):
paste_y=paste_y+IMAGE_SIZE[1]+20
image.paste(Image.new("RGB",IMAGE_SIZE,(0,0,0)),(paste_x,paste_y))
j=j+1
i=i+1
out=NamedTemporaryFile(delete=False)
path=out.name
image.save(out, "PNG")
out.close()
print path
A:
Use itertools.product to iterate over the rows and columns:
import tempfile
import Image
import itertools
COLUMNS=5
ROWS=5
VSEP=20
HSEP=40
IMAGE_SIZE=(100,100)
def draw():
image=Image.new("RGB",
((IMAGE_SIZE[0]+HSEP)*COLUMNS+HSEP,
(IMAGE_SIZE[1]+VSEP)*ROWS+VSEP),
(255,255,255))
for row,column in itertools.product(range(ROWS),range(COLUMNS)):
# print(row,column) # uncomment this to see what itertools.product does
paste_x=HSEP+column*(IMAGE_SIZE[0]+HSEP)
paste_y=VSEP+row*(IMAGE_SIZE[1]+VSEP)
image.paste(Image.new("RGB",IMAGE_SIZE,(0,0,0)),(paste_x,paste_y))
out=tempfile.NamedTemporaryFile(delete=False)
path=out.name
image.save(out, "PNG")
out.close()
print path
draw()
Also, try not to use too many hard-coded numbers. If you put the numbers in variables then your code is easier to change and it cuts down on potential errors.
PS. I think the error in the code you posted is that you never reset paste_y.
After finishing the first column, the value of paste_y just keeps on growing,
so you start pasting small images beyond the lower edge of the image.
So you could fix the problem by moving paste_y=-IMAGE_SIZE[1] to just after j=0, but I still prefer doing it the way I show above.
| Python - PIL - Missing images | Trying to use pil for creating grid-like layout from images. But that code only draws first column. Can anyone help me?
def draw(self):
image=Image.new("RGB",((IMAGE_SIZE[0]+40)*5+40,(IMAGE_SIZE[1]+20)*CHILD_COUNT+20),(255,255,255))
paste_x=(-1)*IMAGE_SIZE[0]
paste_y=(-1)*IMAGE_SIZE[1]
i=0
for a range(5):
paste_x=paste_x+IMAGE_SIZE[0]+40
j=0
for b in range(4):
paste_y=paste_y+IMAGE_SIZE[1]+20
image.paste(Image.new("RGB",IMAGE_SIZE,(0,0,0)),(paste_x,paste_y))
j=j+1
i=i+1
out=NamedTemporaryFile(delete=False)
path=out.name
image.save(out, "PNG")
out.close()
print path
| [
"Use itertools.product to iterate over the rows and columns:\nimport tempfile\nimport Image\nimport itertools\n\nCOLUMNS=5\nROWS=5\nVSEP=20\nHSEP=40\nIMAGE_SIZE=(100,100)\n\ndef draw():\n image=Image.new(\"RGB\",\n ((IMAGE_SIZE[0]+HSEP)*COLUMNS+HSEP,\n (IMAGE_SIZE[1]+VSEP)*... | [
3
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0003907443_python_python_imaging_library.txt |
Q:
Error "AttributeError: 'unicode' object has no attribute 'read'" on file upload
I'm using Pylons to upload an image and store it to disk:
<form method="post">
<input type="file" name="picture" enctype="multipart/form-data" />
</form>
Then in my controller:
if 'picture' in request.POST:
i = ImageHandler()
#Returns full path of image file
picture_file = i.makePath()
shutil.copyfileobj(request.POST['picture'],picture_file)
But I receive the error:
AttributeError: 'unicode' object has no attribute 'read'
What's going on here? Thanks for your help.
A:
Both arguments to copyfileobj are now strings, while that functions takes files (or "file-like objects") as arguments. Do something like
picture_file = open(i.makePath(), 'w')
(or just picture_file = i, not sure what your ImageHandler class is like), then
shutil.copyfileobj(request.POST['picture'].file, picture_file)
| Error "AttributeError: 'unicode' object has no attribute 'read'" on file upload | I'm using Pylons to upload an image and store it to disk:
<form method="post">
<input type="file" name="picture" enctype="multipart/form-data" />
</form>
Then in my controller:
if 'picture' in request.POST:
i = ImageHandler()
#Returns full path of image file
picture_file = i.makePath()
shutil.copyfileobj(request.POST['picture'],picture_file)
But I receive the error:
AttributeError: 'unicode' object has no attribute 'read'
What's going on here? Thanks for your help.
| [
"Both arguments to copyfileobj are now strings, while that functions takes files (or \"file-like objects\") as arguments. Do something like\n picture_file = open(i.makePath(), 'w')\n\n(or just picture_file = i, not sure what your ImageHandler class is like), then\n shutil.copyfileobj(request.POST['picture'].file, p... | [
3
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003907832_pylons_python.txt |
Q:
How to upload a file on FTPS server using m2crypto
I am trying to use ftps to upload file to our FTP server. Login is trivial and works:
from M2Crypto import ftpslib
ftp = ftpslib.FTP_TLS()
ftp.connect(host)
ftp.login(username, password)
as well as descending into directory
for dir in directory:
ftp.cwd(dir)
However, when trying to retrieve directory content:
if directory_name not in ftp.nlst():
ftp.mkd(directory_name)
I get 522 error:
File "/usr/lib/python2.5/ftplib.py", line 459, in nlst
self.retrlines(cmd, files.append)
File "/usr/lib/python2.5/ftplib.py", line 407, in retrlines
conn = self.transfercmd(cmd)
File "/usr/lib/python2.5/ftplib.py", line 356, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "/var/lib/python-support/python2.5/M2Crypto/ftpslib.py", line 86, in ntransfercmd
conn, size = FTP.ntransfercmd(self, cmd, rest)
File "/usr/lib/python2.5/ftplib.py", line 327, in ntransfercmd
resp = self.sendcmd(cmd)
File "/usr/lib/python2.5/ftplib.py", line 241, in sendcmd
return self.getresp()
File "/usr/lib/python2.5/ftplib.py", line 216, in getresp
raise error_perm, resp
ftplib.error_perm: 522 Data connections must be encrypted.
It seems TLS is used only for handshake, not for transfers.
It there a way to secure the transfer (I'd like to upload files using storbinary()) using M2Crypto? If not, what are other alternatives?
A:
Solution is to explicitly call for protected transfer after login():
ftp.prot_p()
| How to upload a file on FTPS server using m2crypto | I am trying to use ftps to upload file to our FTP server. Login is trivial and works:
from M2Crypto import ftpslib
ftp = ftpslib.FTP_TLS()
ftp.connect(host)
ftp.login(username, password)
as well as descending into directory
for dir in directory:
ftp.cwd(dir)
However, when trying to retrieve directory content:
if directory_name not in ftp.nlst():
ftp.mkd(directory_name)
I get 522 error:
File "/usr/lib/python2.5/ftplib.py", line 459, in nlst
self.retrlines(cmd, files.append)
File "/usr/lib/python2.5/ftplib.py", line 407, in retrlines
conn = self.transfercmd(cmd)
File "/usr/lib/python2.5/ftplib.py", line 356, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "/var/lib/python-support/python2.5/M2Crypto/ftpslib.py", line 86, in ntransfercmd
conn, size = FTP.ntransfercmd(self, cmd, rest)
File "/usr/lib/python2.5/ftplib.py", line 327, in ntransfercmd
resp = self.sendcmd(cmd)
File "/usr/lib/python2.5/ftplib.py", line 241, in sendcmd
return self.getresp()
File "/usr/lib/python2.5/ftplib.py", line 216, in getresp
raise error_perm, resp
ftplib.error_perm: 522 Data connections must be encrypted.
It seems TLS is used only for handshake, not for transfers.
It there a way to secure the transfer (I'd like to upload files using storbinary()) using M2Crypto? If not, what are other alternatives?
| [
"Solution is to explicitly call for protected transfer after login():\nftp.prot_p()\n\n"
] | [
4
] | [] | [] | [
"ftp",
"m2crypto",
"python",
"ssl"
] | stackoverflow_0003907826_ftp_m2crypto_python_ssl.txt |
Q:
URL rewriting question
I have a CGI script (pwyky) that I called index.cgi, put in directory wiki/, and setup Apache to call localhost/wiki/index.cgi when I access localhost/wiki.
I'm getting errors when I'm trying to use this application -- it creates a page with links like "http://localhost/wiki/@edit/index", but when I click that link, Apace is trying to serve "wiki/@edit/index" as a file. I suspect that I need to get Apache to pass /@edit/index into index.cgi.
In particular, looking through index.cgi, its looking for strings like "@edit" in REQUEST_URI environment variable.
Any idea how to fix this?
A:
You'd need to show your apache configuration to say for certain, but it seems that Apache isn't actually using mod_cgi to serve the index.cgi script. In your configuration there should be something like 'LoadModule mod_cgi'. It should be uncommented (i.e., it shouldn't have a '#' at the beginning of the line).
If you want to test this, then write a 'Hello World' cgi script and put it (temporarily) in place of index.cgi and see if you can get that to run. Let us know the results.
A:
I found the problem, it turned out this is done through RewriteEngine. Pwyky puts .htaccess file in the directory with all the settings for RewriteEngine, but because AllowOverride is "None" by default on MacOS, they were ignored. The solution was to change all "AllowOverride" directives to "All"
| URL rewriting question | I have a CGI script (pwyky) that I called index.cgi, put in directory wiki/, and setup Apache to call localhost/wiki/index.cgi when I access localhost/wiki.
I'm getting errors when I'm trying to use this application -- it creates a page with links like "http://localhost/wiki/@edit/index", but when I click that link, Apace is trying to serve "wiki/@edit/index" as a file. I suspect that I need to get Apache to pass /@edit/index into index.cgi.
In particular, looking through index.cgi, its looking for strings like "@edit" in REQUEST_URI environment variable.
Any idea how to fix this?
| [
"You'd need to show your apache configuration to say for certain, but it seems that Apache isn't actually using mod_cgi to serve the index.cgi script. In your configuration there should be something like 'LoadModule mod_cgi'. It should be uncommented (i.e., it shouldn't have a '#' at the beginning of the line). \nI... | [
0,
0
] | [] | [] | [
"apache",
"python"
] | stackoverflow_0003897140_apache_python.txt |
Q:
Can I use IronPython to develop GUIs for Google App Engine?
I'm developing a simple Python program with a (dynamic) form interface, but it needs to run on Google App Engine. I understand that IronPython lets one use Visual Studio's drag-and-drop interface builder and classes while programming with Python, but will this be compatible with Google App Engine?
A:
Google's Google App Engine can only run pure python code, and not even all Python is supported. No, you can't do things like IronPython.
If you want to use Python, I'd learn Django. If you want something closer to .NET, I'd go with Java.
| Can I use IronPython to develop GUIs for Google App Engine? | I'm developing a simple Python program with a (dynamic) form interface, but it needs to run on Google App Engine. I understand that IronPython lets one use Visual Studio's drag-and-drop interface builder and classes while programming with Python, but will this be compatible with Google App Engine?
| [
"Google's Google App Engine can only run pure python code, and not even all Python is supported. No, you can't do things like IronPython.\nIf you want to use Python, I'd learn Django. If you want something closer to .NET, I'd go with Java.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"ironpython",
"python",
"user_interface"
] | stackoverflow_0003908062_google_app_engine_ironpython_python_user_interface.txt |
Q:
In Python + Pylons, simple way to copy uploaded file to disk
How can I copy a posted file to disk?
Can I do something like:
file = '/uploaded_files/test.txt'
shutil.copy2(request.POST['file'],file)
Thanks.
A:
You do something like this:
tempfile = request.POST['file']
file_path = 'uploaded_files/' + tempfile.filename # for the original filename
permanent_file = open( file_path, 'wb')
shutil.copyfileobj(tempfile.file, permanent_file)
| In Python + Pylons, simple way to copy uploaded file to disk | How can I copy a posted file to disk?
Can I do something like:
file = '/uploaded_files/test.txt'
shutil.copy2(request.POST['file'],file)
Thanks.
| [
"You do something like this:\ntempfile = request.POST['file']\nfile_path = 'uploaded_files/' + tempfile.filename # for the original filename\npermanent_file = open( file_path, 'wb')\nshutil.copyfileobj(tempfile.file, permanent_file)\n\n"
] | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003907611_pylons_python.txt |
Q:
Non-binary(hex) characters in string received over TCP with Python
maybe this is a noob question, but I'm receiving some data over TCP and when I look at the string I get the following:
\x00\r\xeb\x00\x00\x00\x00\x01t\x00
What is that \r character, and what does the t in \x01t mean?
I've tried Googling, but I'm not sure what to Google for...
thanks.
A:
\r is a carriage return (0x0d), the t is a t.
A:
Viewing binary data in strings can sometimes be confusing, especially if they're long, but you can always convert it to some easier-to-read hex.
>>> data = '\x00\r\xeb\x00\x00\x00\x00\x01t\x00'
>>> ' '.join(["%02X" % ord(char) for char in data])
'00 0D EB 00 00 00 00 01 74 00'
Also, if you're just parsing the byte string into fields, just ignore the string and just go right to unpacking it with the struct module:
>>> import struct
>>> length, command, eggs, spam = struct.unpack('!BBi4s',data)
>>> #...whatever your fields really are
>>> print "len: %i\ncmd: %i\negg qty: %i\nspam flavor: '%s'" % (
... length, command, eggs, spam)
len: 0
cmd: 13
egg qty: -352321536
spam flavor: ' ☺t '
A:
When displaying data as a string, printable characters (such as 't' are displayed as characters, known control sequences are displayed as escapes, and other bytes are displayed in \x## form. Example:
>>> s='\x74\x0d\x99'
>>> s
't\r\x99'
You can dump a hexadecimal form with:
>>> import binascii
>>> binascii.hexlify(s)
'740d99'
| Non-binary(hex) characters in string received over TCP with Python | maybe this is a noob question, but I'm receiving some data over TCP and when I look at the string I get the following:
\x00\r\xeb\x00\x00\x00\x00\x01t\x00
What is that \r character, and what does the t in \x01t mean?
I've tried Googling, but I'm not sure what to Google for...
thanks.
| [
"\\r is a carriage return (0x0d), the t is a t.\n",
"Viewing binary data in strings can sometimes be confusing, especially if they're long, but you can always convert it to some easier-to-read hex.\n>>> data = '\\x00\\r\\xeb\\x00\\x00\\x00\\x00\\x01t\\x00'\n>>> ' '.join([\"%02X\" % ord(char) for char in data])\n'... | [
9,
4,
2
] | [] | [] | [
"bit",
"character",
"networking",
"python"
] | stackoverflow_0003906903_bit_character_networking_python.txt |
Q:
error message when populating cell in 2d numpy array
I am trying to populate data from some csv files into a numpy array with the following code:
PreExArray=zeros([len(TestIDs),numColumns],float)
for row in reader:
if row[1] =='PreEx10SecondsBEFORE':
PreExArray[(j-1),0]=[row[2]]
However, the last line of code above throws the following error:
ValueError: setting an array element with a sequence.
So I printed out the contents of row[2] as follows:
print 'row[2] is: ',row[2]
This produced:
row[2] is: 0.780083333333
So the contents of row[2] are not a sequence as the error message indicates. Instead, the contents are a number.
Therefore, I used to following code to put the contents of row[2] into a variable, then populate PreExArray[(j-1),0] with the contents of that variable, and then print out the contents of that variable:
jones = row[2]
PreExArray[(j-1),0]=jones
print 'PreExArray[(j-1),0] is: ',PreExArray[(j-1),0]
The result is:
PreExArray[(j-1),0] is: 0.780083333333
So, putting row[2] into a variable solves the problem. But this is really sloppy code if I have to put it into a variable every time.
Can anyone show me how to fix the code so that it does not throw an error when I type something a lot simpler, like PreExArray[(j-1),0]=[row[2]] ?
===========================================================================================
OK. I re-wrote the code, and now it is throwing a new error. The new code is as follows:
PreExArray=zeros([len(TestIDs),numColumns],float)
for row in reader:
if row[1] =='PreEx10SecondsBEFORE':
PreExArray[(j-1),0]=row[1]
PreExArray[(j-1),1]=row[2]
This revised code now throws the following error message:
PreExArray[(j-1),0]=row[1]
ValueError: setting an array element with a sequence.
However, when I comment out PreExArray[(j-1),0]=row[1] as follows (#PreExArray[(j-1),0]=row[1]), the subsequent lines run without throwing an error.
Can anyone tell me how to edit this so that it does not continue to throw this error?
A:
You should just have:
PreExArray[(j-1),0]=row[2]
That is, the right hand side should NOT be put into a length-1 list.
A:
It looks like your row variables are from a spreadsheet, and the first index values are row labels (strings). As has been pointed out, you cannot store this data in a numpy array of datatype 'float'.
The error message you get arises from the fact that to numpy, a string looks like a sequence (probably because it supports a len attribute.)
If you want to save the row labels in order to reconstruct a spreadsheet importable file, with the new values you calculate, you will have to store them in a separate list.
| error message when populating cell in 2d numpy array | I am trying to populate data from some csv files into a numpy array with the following code:
PreExArray=zeros([len(TestIDs),numColumns],float)
for row in reader:
if row[1] =='PreEx10SecondsBEFORE':
PreExArray[(j-1),0]=[row[2]]
However, the last line of code above throws the following error:
ValueError: setting an array element with a sequence.
So I printed out the contents of row[2] as follows:
print 'row[2] is: ',row[2]
This produced:
row[2] is: 0.780083333333
So the contents of row[2] are not a sequence as the error message indicates. Instead, the contents are a number.
Therefore, I used to following code to put the contents of row[2] into a variable, then populate PreExArray[(j-1),0] with the contents of that variable, and then print out the contents of that variable:
jones = row[2]
PreExArray[(j-1),0]=jones
print 'PreExArray[(j-1),0] is: ',PreExArray[(j-1),0]
The result is:
PreExArray[(j-1),0] is: 0.780083333333
So, putting row[2] into a variable solves the problem. But this is really sloppy code if I have to put it into a variable every time.
Can anyone show me how to fix the code so that it does not throw an error when I type something a lot simpler, like PreExArray[(j-1),0]=[row[2]] ?
===========================================================================================
OK. I re-wrote the code, and now it is throwing a new error. The new code is as follows:
PreExArray=zeros([len(TestIDs),numColumns],float)
for row in reader:
if row[1] =='PreEx10SecondsBEFORE':
PreExArray[(j-1),0]=row[1]
PreExArray[(j-1),1]=row[2]
This revised code now throws the following error message:
PreExArray[(j-1),0]=row[1]
ValueError: setting an array element with a sequence.
However, when I comment out PreExArray[(j-1),0]=row[1] as follows (#PreExArray[(j-1),0]=row[1]), the subsequent lines run without throwing an error.
Can anyone tell me how to edit this so that it does not continue to throw this error?
| [
"You should just have:\nPreExArray[(j-1),0]=row[2]\n\nThat is, the right hand side should NOT be put into a length-1 list.\n",
"It looks like your row variables are from a spreadsheet, and the first index values are row labels (strings). As has been pointed out, you cannot store this data in a numpy array of data... | [
1,
0
] | [] | [] | [
"2d",
"arrays",
"numpy",
"python"
] | stackoverflow_0003902977_2d_arrays_numpy_python.txt |
Q:
Django Monthly/quartarly grouping of DateField() data
I've got a django model which contains, among other things, a DateField() attribute:
class Table():
date = models.DateField()
value = models.FloatField()
I'm writing a view that groups this data by week, month Quarter and year.
I've hardcoded a calculation that gets my monthly value simply enough - by adding up all the values in that month and deviding by how many entries there were - but I feel like there must be a more elegant way of doing this.
What I'm aiming for is something like this:
get_monthly(Table.objects.all())
>>> [123, 412, 123, 534, 234, 423, 312, 412, 123, 534, 234, 423]
get_quarterly(Table.objects.all())
>>> [123, 412, 123, 534]
Where the values in the list are averages of each month.
Can anyone help me?
A:
You can do this using the model's query capabilities.
Here's an example for the monthly query:
from django.db.models import Avg
Table.objects.extra(select={'month':"strftime('%m',date)"}).values('month').annotate(Avg('value'))
Where you may want to change strftime('%m',date) with month(date) or any other calculation, depending on your database datetime functionality.
| Django Monthly/quartarly grouping of DateField() data | I've got a django model which contains, among other things, a DateField() attribute:
class Table():
date = models.DateField()
value = models.FloatField()
I'm writing a view that groups this data by week, month Quarter and year.
I've hardcoded a calculation that gets my monthly value simply enough - by adding up all the values in that month and deviding by how many entries there were - but I feel like there must be a more elegant way of doing this.
What I'm aiming for is something like this:
get_monthly(Table.objects.all())
>>> [123, 412, 123, 534, 234, 423, 312, 412, 123, 534, 234, 423]
get_quarterly(Table.objects.all())
>>> [123, 412, 123, 534]
Where the values in the list are averages of each month.
Can anyone help me?
| [
"You can do this using the model's query capabilities.\nHere's an example for the monthly query:\nfrom django.db.models import Avg\nTable.objects.extra(select={'month':\"strftime('%m',date)\"}).values('month').annotate(Avg('value'))\n\nWhere you may want to change strftime('%m',date) with month(date) or any other c... | [
3
] | [] | [] | [
"datefield",
"django",
"django_models",
"python"
] | stackoverflow_0003907240_datefield_django_django_models_python.txt |
Q:
Sending data to django server from a non-django server
I am making a bookmarklet where I need people to login first. My question is how do I send login credentials to the django server from a different domain?
I was thinking there were a couple ways, since I can't use send data via request.
Generate the sha1 algo on the client-side...but then how do I know what Django is salting with and how can I make that secure?
Find a way to send some post data to my server from a different domain.
Any other ideas/implementations?
Much appreciated
A:
You can send the POST data (via SSL of course) to your Django site. Your view will handle the request. If you post to that view, you can authenticate using django.contrib.auth methods. The following was taken from http://docs.djangoproject.com/en/dev/topics/auth/
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Send success message.
else:
# Return a 'disabled account' error message
else:
# Return an 'invalid login' error message.
| Sending data to django server from a non-django server | I am making a bookmarklet where I need people to login first. My question is how do I send login credentials to the django server from a different domain?
I was thinking there were a couple ways, since I can't use send data via request.
Generate the sha1 algo on the client-side...but then how do I know what Django is salting with and how can I make that secure?
Find a way to send some post data to my server from a different domain.
Any other ideas/implementations?
Much appreciated
| [
"You can send the POST data (via SSL of course) to your Django site. Your view will handle the request. If you post to that view, you can authenticate using django.contrib.auth methods. The following was taken from http://docs.djangoproject.com/en/dev/topics/auth/\nif request.method == 'POST':\n username = re... | [
1
] | [] | [] | [
"bookmarklet",
"django",
"javascript",
"python"
] | stackoverflow_0003908523_bookmarklet_django_javascript_python.txt |
Q:
Python: Google Checkout Signature Function
I am attempting to integrate Google Checkout into my website. I have created the following function for generating the hmac-sha-1 signature requred:
def make_signature(cart_xml):
import hmac
import hashlib
import base64
# The number is a psuedo-merchantID, cart_xml contains a string with the
# shopping cart xml as outlined on google's documentation.
signature = hmac.new("711348421531236", cart_xml, hashlib.sha1)
signature = base64.b64encode(signature.digest())
return signature
I based this code off of the requirements outlined on http://code.google.com/apis/checkout/developer/Google_Checkout_XML_API.html#create_checkout_cart
However, I cannot get my cart to validate the signature. I keep receiving the following error: "Bad Signature on Cart"
Does anyone know how to fix this?
A:
Figured it out. I was using the Merchant ID instead of the Merchant Key.
| Python: Google Checkout Signature Function | I am attempting to integrate Google Checkout into my website. I have created the following function for generating the hmac-sha-1 signature requred:
def make_signature(cart_xml):
import hmac
import hashlib
import base64
# The number is a psuedo-merchantID, cart_xml contains a string with the
# shopping cart xml as outlined on google's documentation.
signature = hmac.new("711348421531236", cart_xml, hashlib.sha1)
signature = base64.b64encode(signature.digest())
return signature
I based this code off of the requirements outlined on http://code.google.com/apis/checkout/developer/Google_Checkout_XML_API.html#create_checkout_cart
However, I cannot get my cart to validate the signature. I keep receiving the following error: "Bad Signature on Cart"
Does anyone know how to fix this?
| [
"Figured it out. I was using the Merchant ID instead of the Merchant Key.\n"
] | [
0
] | [] | [] | [
"google_checkout",
"payment_gateway",
"python"
] | stackoverflow_0003902667_google_checkout_payment_gateway_python.txt |
Q:
Check if Session Key is set
I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there any way to check if a session is set, so that it can be set if it doesn't exist?
A:
I assume that you want to check if a key is set in session, not if a session is set (don't know what the latter means). If so:
You can do:
if key not in request.session:
# Set it.
In your case:
if 'cart' not in request.session:
# Set it.
EDIT: changed the code snippet to use key not in rather than not key in. Thanks @katrielalex.
A:
You can use the get-method on the session dictionary, it will not throw an error if the key doesn't exist, but return none as a default value or your custom default value:
cart = request.session.get('cart')
cart = request.session.get('cart', 'no cart')
| Check if Session Key is set | I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there any way to check if a session is set, so that it can be set if it doesn't exist?
| [
"I assume that you want to check if a key is set in session, not if a session is set (don't know what the latter means). If so:\nYou can do:\nif key not in request.session:\n # Set it.\n\nIn your case:\nif 'cart' not in request.session:\n # Set it.\n\nEDIT: changed the code snippet to use key not in rather th... | [
53,
19
] | [] | [] | [
"django",
"django_sessions",
"python"
] | stackoverflow_0003908761_django_django_sessions_python.txt |
Q:
Why are CherryPy object attributes persistent between requests?
I was writing debugging methods for my CherryPy application. The code in question was (very) basically equivalent to this:
import cherrypy
class Page:
def index(self):
try:
self.body += 'okay'
except AttributeError:
self.body = 'okay'
return self.body
index.exposed = True
cherrypy.quickstart(Page(), config='root.conf')
I was surprised to notice that from request to request, the output of self.body grew. When I visited the page from one client, and then from another concurrently-open client, and then refreshed the browsers for both, the output was an ever-increasing string of "okay"s. In my debugging method, I was also recording user-specific information (i.e. session data) and that, too, showed up in both users' output.
I'm assuming that's because the python module is loaded into working memory instead of being re-run for every request.
My question is this: How does that work? How is it that self.debug is preserved from request to request, but cherrypy.session and cherrypy.response aren't?
And is there any way to set an object attribute that will only be used for the current request? I know I can overwrite self.body per every request, but it seems a little ad-hoc. Is there a standard or built-in way of doing it in CherryPy?
(second question moved to How does CherryPy caching work?)
A:
You hit the nail on the head with the observation that you're getting the same data from self.body because it's the same in memory of the Python process running CherryPy.
self.debug maintains 'state' for this reason, it's an attribute of the running server.
To set data for the current session, use cherrypy.session['fieldname'] = 'fieldvalue', to get data use cherrypy.session.get('fieldname').
You (the programmer) do not need to know the session ID, cherrypy.session handles that for you -- the session ID is automatically generated on the fly by cherrypy and is persisted by exchanging a cookie between the browser and server on subsequent query/response interactions.
If you don't specify a storage_type for cherrypy.session in your config, it'll be stored in memory (accessible to the server and you), but you can also store the session files on disk if you wish which might be a handy way for you to debug without having to write a bunch of code to dig out session IDs or key/pair values from the running server.
For more info check out http://www.cherrypy.org/wiki/CherryPySessions
A:
synthesizerpatel's analysis is correct, but if you really want to store some data per request, then store it as an attribute on cherrypy.request, not in the session. The cherrypy.request and .response objects are new for each request, so there's no fear that any of their attributes will persist across requests. That is the canonical way to do it. Just make sure you're not overwriting any of cherrypy's internal attributes! cherrypy.request.body, for example, is already reserved for handing you, say, a POSTed JSON request body.
For all the details of exactly how the scoping works, the best source is the source code.
| Why are CherryPy object attributes persistent between requests? | I was writing debugging methods for my CherryPy application. The code in question was (very) basically equivalent to this:
import cherrypy
class Page:
def index(self):
try:
self.body += 'okay'
except AttributeError:
self.body = 'okay'
return self.body
index.exposed = True
cherrypy.quickstart(Page(), config='root.conf')
I was surprised to notice that from request to request, the output of self.body grew. When I visited the page from one client, and then from another concurrently-open client, and then refreshed the browsers for both, the output was an ever-increasing string of "okay"s. In my debugging method, I was also recording user-specific information (i.e. session data) and that, too, showed up in both users' output.
I'm assuming that's because the python module is loaded into working memory instead of being re-run for every request.
My question is this: How does that work? How is it that self.debug is preserved from request to request, but cherrypy.session and cherrypy.response aren't?
And is there any way to set an object attribute that will only be used for the current request? I know I can overwrite self.body per every request, but it seems a little ad-hoc. Is there a standard or built-in way of doing it in CherryPy?
(second question moved to How does CherryPy caching work?)
| [
"You hit the nail on the head with the observation that you're getting the same data from self.body because it's the same in memory of the Python process running CherryPy.\nself.debug maintains 'state' for this reason, it's an attribute of the running server.\nTo set data for the current session, use cherrypy.sessi... | [
5,
5
] | [] | [] | [
"cherrypy",
"persistent",
"python",
"request"
] | stackoverflow_0003898482_cherrypy_persistent_python_request.txt |
Q:
python regex question
What is the correct regex statement using re.search() to find and return a file extension in a string.
Such as:
(.+).(avi|rar|zip|txt)
I need it to search a string and if it contains any of those avi, rar, etc) return just that extension.
Thanks!
EDIT: should add that is needs to be case insensitive
A:
the standard library is better ;)
>>> os.path.splitext('hello.py')
('hello', '.py')
A:
You need:
(.)\.(avi|rar|zip|txt)$
Note the backslash to escape the dot. This will make it look for a literal dot rather than any character.
To make it case insensitive, use the RE.I flag in your search call.
re.search(r'(.)\.(avi|rar|zip|txt)$', string, re.I)
A:
Short interactive run:
>>> import re
>>> pat="(.+)\.(avi|rar|zip|txt)"
>>> re.search(pat, "abcdefg.zip", re.IGNORECASE).groups()
('abcdefg', 'zip')
>>> re.search(pat, "abcdefg.ZIP", re.IGNORECASE).groups()
('abcdefg', 'ZIP')
>>>
A:
(.+)[.](avi|rar|zip|txt)
Then the group 2 will be extension.
I have just written a blog about Regular Expression
http://blogs.appframe.com/erikv/2010-09-23-Regular-Expression
if you want to read more about this.
A:
Since I think regex is evil...
def return_extension(filename):
'''(This functions assumes that filenames such as `.foo` have extension
`foo`.)
'''
tokens = filename.split('.')
return '' if len(tokens) == 1 else tokens[-1]
...I advocate simply parsing the filename.
A:
If you know that the extension is at the very end of the string, this should work well:
.\.(avi|rar|zip|txt)$
The first bit will ensure that there's some character before the dot.
The $ specifies that the file extension is at the end of the string, i.e. the $ means "the string ends here". For gory details on this, including some edge cases with newlines that you should be aware of see the comment discussion for JoshD's answer, as well as the entry for $ in the docs.
So then the only entry in the match.groups() tuple, i.e. match.groups()[0], will be the extension itself.
| python regex question | What is the correct regex statement using re.search() to find and return a file extension in a string.
Such as:
(.+).(avi|rar|zip|txt)
I need it to search a string and if it contains any of those avi, rar, etc) return just that extension.
Thanks!
EDIT: should add that is needs to be case insensitive
| [
"the standard library is better ;) \n>>> os.path.splitext('hello.py')\n('hello', '.py')\n\n",
"You need:\n(.)\\.(avi|rar|zip|txt)$\n\nNote the backslash to escape the dot. This will make it look for a literal dot rather than any character.\nTo make it case insensitive, use the RE.I flag in your search call.\nre.s... | [
8,
6,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003908727_python_regex.txt |
Q:
combination of coverage and profiler?
I really like the python coverage module:
http://nedbatchelder.com/code/coverage/
and the HTML pages it generates. Is there a combination of this and profiling so that one could see a unified HTML report of coverage+profiling.
Thanks in advance.
A:
Thanks, reckoner, glad that you like the HTML output from coverage. I've never done anything to combine it with a profiler, and haven't heard of anyone else doing it either.
When I created the HTML output, I had in the back of my mind the idea of having it be a generalized source-code-with-tool-annotations facility, but it was enough work just getting it built only for coverage!
| combination of coverage and profiler? | I really like the python coverage module:
http://nedbatchelder.com/code/coverage/
and the HTML pages it generates. Is there a combination of this and profiling so that one could see a unified HTML report of coverage+profiling.
Thanks in advance.
| [
"Thanks, reckoner, glad that you like the HTML output from coverage. I've never done anything to combine it with a profiler, and haven't heard of anyone else doing it either.\nWhen I created the HTML output, I had in the back of my mind the idea of having it be a generalized source-code-with-tool-annotations facil... | [
4
] | [] | [] | [
"code_coverage",
"profiling",
"python"
] | stackoverflow_0003907923_code_coverage_profiling_python.txt |
Q:
Handling graceful degradation within a Django form
I have a form that looks similar to the following (simplified for brevity):
PRICING_PATTERN = r'(?:^\$?(?P<flat_price>\d+|\d?\.\d\d)$)|(?:^(?P<percent_off>\d+)\s*\%\s*off$)'
class ItemForm(forms.Form):
pricing = forms.RegexField(
label='Pricing',
regex=PRICING_PATTERN
)
pricing_type = forms.CharField(
label='Deal type',
widget=forms.RadioSelect(
choices=(
('flat_price','Flat price'),
('percent_off','Percentage off'),
),
attrs={'style': 'display: none;'})
),
)
pricing_flat_price = forms.DecimalField(
label='Flat price',
max_digits=5,
decimal_places=2,
widget=forms.TextInput(attrs={'style': 'display: none;'})
)
pricing_percent_off = forms.IntegerField(
label='Percent off',
required=False,
min_value=0,
max_value=100,
widget=forms.TextInput(attrs={'style': 'display: none;'})
)
Initially, for the purpose of graceful degradation, only pricing is visible. If the user has javascript enabled, I hide pricing and make pricing_type visible. Now, on a pricing_type radio selection, I make either pricing_flat_cost or pricing_percent_off visible. This makes for a more precise and user-friendly UI.
My questions: How should I go about coding the logic that figures out where to take the values from---the RegexField or the pricing_flat_price and pricing_percent_off fields? Should I perhaps create a function in ItemForm that figures it out and returns the correct value?
Or perhaps there's a cleaner approach that someone could suggest?
A:
Define a custom widget for the type selection and include the JavaScript code as a separate .js file.
| Handling graceful degradation within a Django form | I have a form that looks similar to the following (simplified for brevity):
PRICING_PATTERN = r'(?:^\$?(?P<flat_price>\d+|\d?\.\d\d)$)|(?:^(?P<percent_off>\d+)\s*\%\s*off$)'
class ItemForm(forms.Form):
pricing = forms.RegexField(
label='Pricing',
regex=PRICING_PATTERN
)
pricing_type = forms.CharField(
label='Deal type',
widget=forms.RadioSelect(
choices=(
('flat_price','Flat price'),
('percent_off','Percentage off'),
),
attrs={'style': 'display: none;'})
),
)
pricing_flat_price = forms.DecimalField(
label='Flat price',
max_digits=5,
decimal_places=2,
widget=forms.TextInput(attrs={'style': 'display: none;'})
)
pricing_percent_off = forms.IntegerField(
label='Percent off',
required=False,
min_value=0,
max_value=100,
widget=forms.TextInput(attrs={'style': 'display: none;'})
)
Initially, for the purpose of graceful degradation, only pricing is visible. If the user has javascript enabled, I hide pricing and make pricing_type visible. Now, on a pricing_type radio selection, I make either pricing_flat_cost or pricing_percent_off visible. This makes for a more precise and user-friendly UI.
My questions: How should I go about coding the logic that figures out where to take the values from---the RegexField or the pricing_flat_price and pricing_percent_off fields? Should I perhaps create a function in ItemForm that figures it out and returns the correct value?
Or perhaps there's a cleaner approach that someone could suggest?
| [
"Define a custom widget for the type selection and include the JavaScript code as a separate .js file.\n"
] | [
1
] | [] | [] | [
"django_forms",
"graceful_degradation",
"python"
] | stackoverflow_0003909564_django_forms_graceful_degradation_python.txt |
Q:
Jython test coverage
I'm trying to use Jython instead of Python for a project (want jdbc driver for a sort of rare database).
Everything is working OK so far, but I can't find any good tools for code coverage. Does anyone have a solution to this?
The googling I've done seems to indicate that jython is missing some things that code coverage tools need. http://nedbatchelder.com/blog/201005/coveragepy_on_jython.html
How do others solve this? I suppose something like jpype together with normal python would be a way forward, but I would rather not introduce jpype in my environment just for coverage measurements.
A:
How do others solve this?
Your question is fundamentally, "how can I get tools for languages that don't have built-in tool support?" The hypermodern solution for programming langauges is to try to build in all the necessary support into the particular langauge implementations (reflection, profiling, metaprogramming, ...). While its a nice idea, the amount of engineering required to do it is huge, and .... it often doesn't happen (witness your issue with Jython).
Another way to solve the problem is to step outside the language (or its implementation) and get meta tool building support from engines that are designed to implement tools across a wide variety of languages. That requires engineering, too, but it can be done in pretty general way so that the meta-tool is widely usable. Such meta tools can then be used to implement the tools you don't have.
Our DMS Software Reengineering Toolkit is such a meta tool, providing program parsing, analysis, and transformation, parameterized by explicit langauge definitions. DMS has support for many languages (C, C++, C#, COBOL, Java, PHP, ...) including Python, and it supports dialects, enabling it to handle variations on the "standard" langauge (I suspect Jython is not exactly Python).
At this link you can find a technical paper on how a meta-tool like DMS can be used to implement test coverage for arbitrary langauges. This idea has been used to implement a family of test coverage tools available from my company. (We're likely to do this for Python at some point in the future).
A:
The blog post you link mentions that you can run "coverage run" under Jython, then "coverage html" under CPython. Did you try this? It should give reasonable results.
| Jython test coverage | I'm trying to use Jython instead of Python for a project (want jdbc driver for a sort of rare database).
Everything is working OK so far, but I can't find any good tools for code coverage. Does anyone have a solution to this?
The googling I've done seems to indicate that jython is missing some things that code coverage tools need. http://nedbatchelder.com/blog/201005/coveragepy_on_jython.html
How do others solve this? I suppose something like jpype together with normal python would be a way forward, but I would rather not introduce jpype in my environment just for coverage measurements.
| [
"How do others solve this?\nYour question is fundamentally, \"how can I get tools for languages that don't have built-in tool support?\" The hypermodern solution for programming langauges is to try to build in all the necessary support into the particular langauge implementations (reflection, profiling, metaprog... | [
1,
1
] | [] | [] | [
"code_coverage",
"jython",
"python"
] | stackoverflow_0003902350_code_coverage_jython_python.txt |
Q:
MEDIA_URL tuple
I would like to write a context_processor, something like this:
settings.py:
MEDIA_URLS = ('cname2.example.com/media', 'cname3.example.com/media',)
TEMPLATE_CONTEXT_PROCESSORS = (
"util.context_processors.media",
)
util/context_processors.py
from random import choice
from django.conf import settings
def media(request):
"""
Adds random media-related context variable to the context.
"""
def get_media_url():
return choice(settings.MEDIA_URLS)
return {'MEDIA_URL': get_media_url()}
I have MEDIA_URL many places on the template and I'd like each instance to be chosen randomly so that I get a mix of cnames on any given page in order to reduce the number of requests to any given static url at a time. Any thoughts on how best to do this?
A:
Like so, although the exact routine to select the next element is up to you.
| MEDIA_URL tuple | I would like to write a context_processor, something like this:
settings.py:
MEDIA_URLS = ('cname2.example.com/media', 'cname3.example.com/media',)
TEMPLATE_CONTEXT_PROCESSORS = (
"util.context_processors.media",
)
util/context_processors.py
from random import choice
from django.conf import settings
def media(request):
"""
Adds random media-related context variable to the context.
"""
def get_media_url():
return choice(settings.MEDIA_URLS)
return {'MEDIA_URL': get_media_url()}
I have MEDIA_URL many places on the template and I'd like each instance to be chosen randomly so that I get a mix of cnames on any given page in order to reduce the number of requests to any given static url at a time. Any thoughts on how best to do this?
| [
"Like so, although the exact routine to select the next element is up to you.\n"
] | [
1
] | [] | [] | [
"django",
"optimization",
"python"
] | stackoverflow_0003909644_django_optimization_python.txt |
Q:
VoIP in Python then http
Hello there
i wanted to know if it was possible to make a voip script in python and then if it works integrate it online on my web site
thanks a bunch
A:
you are very vague if you ask me.
I guess it is possible because there are SIP libraries in python.
| VoIP in Python then http | Hello there
i wanted to know if it was possible to make a voip script in python and then if it works integrate it online on my web site
thanks a bunch
| [
"you are very vague if you ask me.\nI guess it is possible because there are SIP libraries in python.\n"
] | [
2
] | [] | [] | [
"php",
"python",
"voice",
"voip"
] | stackoverflow_0003907721_php_python_voice_voip.txt |
Q:
Calculating sliding averages
I'm not even sure what sliding average is, but someone told me it would help with something I'm working on.
I have a table of random values -- table[n] = random(100) / 100
I need to populate table2 with their sliding averages.
I think this is the terminology. Let me know if it doesn't make sense.
A:
The Moving average entry on Wikipedia might be a good start.
A:
"Sliding Average" is another term for "Moving Average" AKA "Boxcar Average".
All are a form of Smoothing the data.
| Calculating sliding averages | I'm not even sure what sliding average is, but someone told me it would help with something I'm working on.
I have a table of random values -- table[n] = random(100) / 100
I need to populate table2 with their sliding averages.
I think this is the terminology. Let me know if it doesn't make sense.
| [
"The Moving average entry on Wikipedia might be a good start.\n",
"\"Sliding Average\" is another term for \"Moving Average\" AKA \"Boxcar Average\". \nAll are a form of Smoothing the data. \n"
] | [
7,
2
] | [] | [] | [
"c",
"javascript",
"python",
"sliding"
] | stackoverflow_0003909487_c_javascript_python_sliding.txt |
Q:
What's the easiest way to add commas to an integer?
Possible Duplicate:
How to print number with commas as thousands separators?
For example:
>> print numberFormat(1234)
>> 1,234
Or is there a built-in function in Python that does this?
A:
No one so far has mentioned the new ',' option which was added in version 2.7 to the Format Specification Mini-Language -- see PEP 378: Format Specifier for Thousands Separator in the What's New in Python 2.7 document. It's easy to use because you don't have to mess around with locale (but is limited for internationalization due to that, see the original PEP 378). It works with floats, ints, and decimals — and all the other formatting features provided for in the mini-language spec.
Sample usage:
print format(1234, ",d") # -> 1,234
print "{:,d}".format(1234) # -> 1,234
print(f'{1234:,d}') # -> 1,234 (Python 3.6+)
Note: While this new feature is definitely handy, it's actually not all that much harder to use the locale module, as several others have suggested. The advantage is that then numeric output can be made to automatically follow the proper thousands (and other) separator conventions used in various countries when outputting things like numbers, dates, and times. It's also very easy to put the default settings from your computer into effect without learning a bunch of language and country codes. All you need to do is:
import locale
locale.setlocale(locale.LC_ALL, '') # empty string for platform's default settings
After doing that you can just use the generic 'n' type code for outputting numbers (both integer and float). Where I am, commas are used as the thousand separator, so after setting the locale as shown above, this is what would happen:
print format(1234, "n") # -> 1,234
print "{:n}".format(1234) # -> 1,234
Much of the rest of the world uses periods instead of commas for this purpose, so setting the default locale in many locations (or explicitly specifying the code for such a region in a setlocale() call) produces the following:
print format(1234, "n") # -> 1.234
print "{:n}".format(1234) # -> 1.234
Output based on the 'd' or ',d' formatting type specifier is unaffected by the use (or non-use) of setlocale(). However the 'd' specifier is affected if you instead use the locale.format() or locale.format_string() functions.
A:
locale.format()
Don't forget to set the locale appropriately first.
A:
Stripped from webpy utils.py:
def commify(n):
"""
Add commas to an integer `n`.
>>> commify(1)
'1'
>>> commify(123)
'123'
>>> commify(1234)
'1,234'
>>> commify(1234567890)
'1,234,567,890'
>>> commify(123.0)
'123.0'
>>> commify(1234.5)
'1,234.5'
>>> commify(1234.56789)
'1,234.56789'
>>> commify('%.2f' % 1234.5)
'1,234.50'
>>> commify(None)
>>>
"""
if n is None: return None
n = str(n)
if '.' in n:
dollars, cents = n.split('.')
else:
dollars, cents = n, None
r = []
for i, c in enumerate(str(dollars)[::-1]):
if i and (not (i % 3)):
r.insert(0, ',')
r.insert(0, c)
out = ''.join(r)
if cents:
out += '.' + cents
return out
There are other solutions here.
A:
Use locale.format() on the integer, but beware of the current locale on your environment. Some environments may not have this set or set to something that won't give you a commafied result.
Here's some code I had to write to deal with this exact issue. It'll automatically set the locale for you depending on your platform:
try:
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #use locale.format for commafication
except locale.Error:
locale.setlocale(locale.LC_ALL, '') #set to default locale (works on windows)
score = locale.format('%d', player['score'], True)
| What's the easiest way to add commas to an integer? |
Possible Duplicate:
How to print number with commas as thousands separators?
For example:
>> print numberFormat(1234)
>> 1,234
Or is there a built-in function in Python that does this?
| [
"No one so far has mentioned the new ',' option which was added in version 2.7 to the Format Specification Mini-Language -- see PEP 378: Format Specifier for Thousands Separator in the What's New in Python 2.7 document. It's easy to use because you don't have to mess around with locale (but is limited for internati... | [
102,
13,
12,
5
] | [] | [] | [
"number_formatting",
"python"
] | stackoverflow_0003909457_number_formatting_python.txt |
Q:
Django - Form widget with a checkbox to choose between unlimited or a textbox for a number
I am making a form in Django. The field to display is a numeric field representing some limit. It's possible for there to be no limit. Rather than force the user to enter some strange number to mean unlimited (e.g. -1), I'd like there to be a radio button, with 2 options: "Unlimited" and the second option being a text box that the user can enter the value into.
The original model only has the IntegerField which can be null. A null value is used to mean unlimited. Is there some way I can make a FormField of this field that will include this checkbox functionality?
I know I can hand write the HTML myself, I'm wondering if there is a already made django field/widget that'll do this.
A:
You can either make the form have an additional form field for the checkbox. And override it's save method to fill the model fields accordingly. Or you can make a custom form field widget that would hold both HTML input fields and produce the appropriate python value from the inputs and vice versa. The first option being the simpler to implement, and wiser if you need this functionality only in one form. Either way, I'd reconsider using a null value to mean anything except no value entered. You could make it so that the Integer field holds -1 to mean unlimited if all other user specified values can only be positive. Or add another boolean model field to hold the value for this checkbox.
| Django - Form widget with a checkbox to choose between unlimited or a textbox for a number | I am making a form in Django. The field to display is a numeric field representing some limit. It's possible for there to be no limit. Rather than force the user to enter some strange number to mean unlimited (e.g. -1), I'd like there to be a radio button, with 2 options: "Unlimited" and the second option being a text box that the user can enter the value into.
The original model only has the IntegerField which can be null. A null value is used to mean unlimited. Is there some way I can make a FormField of this field that will include this checkbox functionality?
I know I can hand write the HTML myself, I'm wondering if there is a already made django field/widget that'll do this.
| [
"You can either make the form have an additional form field for the checkbox. And override it's save method to fill the model fields accordingly. Or you can make a custom form field widget that would hold both HTML input fields and produce the appropriate python value from the inputs and vice versa. The first optio... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003904809_django_django_forms_python.txt |
Q:
OCSP command-line test tool?
Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program
A:
Looking a bit more, I think I've found some answers:
a) OpenSSL at the rescue:
openssl ocsp -whatever
For more info, http://www.openssl.org/docs/apps/ocsp.html
b) http://www.openvalidation.org/ is another way of testing a cert. And via its links, I got to:
http://security.polito.it/tools/ocsp/
Ascertia OCSP Client tool (http://www.ascertia.com/products/ocsptool/)
Ascertia OCSP Crusher tool (an OCSP load generator) (http://www.ascertia.com/products/ocspCrusher/)
Thanks to all the answers!
A:
The newpki client claims to be able to do that.
http://www.newpki.org/
A:
bouncycastle has a Java crypto-provider and support for OCSP requests and responses. The differences between OCSPReq and OCSPRequest and OCSPResp and OCSPResponse class are a little confusing, though.
A:
Here is a good ressource to have a simple OCSP Client or OCSP Responder with OpenSSL : http://backreference.org/2010/05/09/ocsp-verification-with-openssl/
A:
Can you test it over HTTP as described in the specs in Appendix A? If so, then you can use any web test util. Since you mentioned Java, JMeter comes to mind. With JMeter, you can create your java code to do validation, etc and re-use it in your test cases.
Can you use something other than CMD line, such as a BASH script via Cygwin?
You'd still have to script some things to validate the test, perhaps using openssl?
curl http://some.ocsp.url/ > resp.der
openssl ocsp -respin resp.der -text
See page http://www.ietf.org/rfc/rfc2560.txt
| OCSP command-line test tool? | Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program
| [
"Looking a bit more, I think I've found some answers:\na) OpenSSL at the rescue:\nopenssl ocsp -whatever\n\nFor more info, http://www.openssl.org/docs/apps/ocsp.html\nb) http://www.openvalidation.org/ is another way of testing a cert. And via its links, I got to:\n\nhttp://security.polito.it/tools/ocsp/\nAscertia O... | [
4,
1,
1,
1,
0
] | [] | [] | [
"command_line",
"java",
"ocsp",
"python"
] | stackoverflow_0000071468_command_line_java_ocsp_python.txt |
Q:
How to generate a predictable shuffling of a sequence without generating the whole sequence in advance?
The following python code describes exactly what I want to achieve for a sequence of arbitrary size (population):
import random
fixed_seed = 1 #generate the same sequence every time with a fixed seed
population = 1000
sample_count = 5 #demonstration number
num_retries = 3 #just enough to show the repeatable behaviour
for trynum in xrange(num_retries):
#generate the fresh/ordered sequence (0->population)...
seq = range(population)
#seed the random number generator the same way every time...
random.seed(fixed_seed)
#shuffle the sequence...
random.shuffle(seq)
#display results for this try...
sample_sequence = [str(x) for x in seq[:sample_count]]
print "try %s: %s..." % (trynum + 1, ", ".join(sample_sequence))
#Sample output...
#try 1: 995, 721, 62, 326, 541...
#try 2: 995, 721, 62, 326, 541...
#try 3: 995, 721, 62, 326, 541...
The problem with that method is that it requires generating the entire
sequence in memory first. This can be a problem for huge populations.
Note that a potentially big advantage of this method is that you can pick off any array position at any time.
Now - If the problem at hand happens to let you set the population size to a power of two
(minus 1), a Linear Feedback Shift Register can be used to get the predictable random sequence. LFSRs are neat, and explained pretty well in the wikipedia article on them.
The python code below demonstrates this (and I did a pile of uniqueness testing to ensure it works as advertised). See the wikipedia article again for an explanation of how the code works (Galois configuration).
TAP_MASKS = { #only one needed, but I included 3 to make the code more useful
10: 0x00000240, #taps at 10, 7
16: 0x0000B400, #taps at 16, 14, 13, 11
32: 0xE0000200, #taps at 32, 31, 30, 10
}
def MaxLengthLFSR(seed, register_length):
"Gets next value from seed in max-length LFSR using Galois configuration."
lsb = seed & 1
next_val = seed >> 1
if lsb == 1:
mask = TAP_MASKS[register_length]
next_val ^= mask
return next_val
reglen = 16 #number of bits in register
population = (2**reglen) - 1 #not used, just showing it
fixed_seed = 1 #seed == startval in this case (could randomize in population)
sample_count = 5 #demonstration number
num_retries = 3 #just enough to show the repeatable behaviour
for trynum in xrange(num_retries):
next_val = fixed_seed
seq = [fixed_seed, ]
for x in xrange(sample_count - 1):
next_val = MaxLengthLFSR(next_val, reglen)
seq.append(next_val)
seq = [str(x) for x in seq]
print "try %s: %s..." % (trynum + 1, ", ".join(seq))
#Sample output...
#try 1: 1, 46080, 23040, 11520, 5760...
#try 2: 1, 46080, 23040, 11520, 5760...
#try 3: 1, 46080, 23040, 11520, 5760...
This is nice because you can have a HUGE population and easily calculate a repeatable non-repeating random number sequence without using a big chunk of memory.
The drawbacks are a) that it is limited to a "shuffling" sequences of size (2**N - 1), and b) that you cannot determine what the value of a particular position in the random sequence is at an arbitrary location. You need to know the value at a particular point and walk the sequence from there.
The latter (b) is mostly ok since most of the time you'll generate the sequence in order, so you just need to remember the last value. The power of 2 limitation (a) is kind of a deal killer,though... depending on the application.
How do you achieve maximum-length-LFSR-like non-repeating results for arbitrary sequence lengths?
As a bonus, it would be nice to have a solution where you are able to know the number at a given sequence position without needing to walk through the sequence to that position.
Note: if you want a good starting set of LFSR tap locations for maximum-length LFSRs (ones that generate the whole register population without repeating once), this link is quite good and has a huge number of tap locations per register size (up to 32 bits, anyway).
Also please note that I've seen many questions closely related to my question and shuffling/LFSR, but none of them exactly relate to what I'm after (predictable shuffle of arbitrary size linear sequence). Or at least as far as I have been able to understand them, anyway.
I've recently been looking into Linear Congruential Generators, which seem promising, but I haven't been able to get them to work yet. Rather than sitting on the question further I'll ask it, and post the answer if I figure it out and they work.
A:
I've actually written about this before: Secure Permutations with Block Ciphers. In a nutshell:
Yes, you can use an LFSR to generate permutations with a length that's a power of 2. You can also use any block cipher. With a block cipher, you can also find the element at index n, or the index for element n.
To generate a permutation with arbitrary length l, create one with the smallest power of 2 length greater than l. When you want to find the nth permutation element, apply the permutation function, and if it generates a number outside the desired range, apply it again; repeat until the number is in the acceptable range.
The number of iterations required for step 2 will average no more than 2; the worst case is high, but extremely unlikely to occur.
A:
First off, note that this isn't a random sequence. It only generates a single, fixed, repeating sequence, and the seed chooses where in the sequence you start. That's the same as all PRNGs, of course, but normally the cycle of a PRNG is much larger than 16-bit or 32-bit. The way you've described using it, the cycle length is equal to the number of items you're iterating over, so all it'll do is take a single "shuffled" order and change where you start. The "seed" value is more like a starting index than a seed.
It's not the most satisfactory answer, but it's probably practical: you can pad the length to the next power of two, and skip any indexes above the actual maximum. Thus, if you have 5000 items, generate a sequence over 8192 items, and discard any results between [5000,8191]. The overhead from this sounds ugly, but in perspective it's not that bad: since this can at most double the length of the list, on average you'll have to discard one out of two results, so the worst-case average overhead is doubling the amount of work.
The following code demonstrates this (as well as showing a cleaner way to implement it). The third parameter to MaxLengthLFSR, if given, is the actual maximum value. You'd probably want to fill in TAP_MASKS for a larger number of sizes and then choose the smallest register size that fits the requested sequence length; here we just use the one requested, which works but will cause much more overhead if the length of the sequence is much larger than it needs to be.
TAP_MASKS = { # only one needed, but I included 3 to make the code more useful
10: 0x00000240, # taps at 10, 7
16: 0x0000B400, # taps at 16, 14, 13, 11
32: 0xE0000200, # taps at 32, 31, 30, 10
}
def MaxLengthLFSR(next_val, reglen, max_value=None):
"""Iterate values from seed in max-length LFSR using Galois configuration."""
# Ensure that max_value isn't 0, or we'll infinitely loop without yielding any values.
if max_value is not None:
assert max_value > 0
while True:
if max_value is None or next_val < max_value:
yield next_val
lsb = next_val & 1
next_val = next_val >> 1
if lsb == 1:
mask = TAP_MASKS[reglen]
next_val ^= mask
sample_count = 5 # demonstration number
num_retries = 3 # just enough to show the repeatable behaviour
for trynum in xrange(num_retries):
it = MaxLengthLFSR(1, 16, 2000)
seq = []
for x in xrange(sample_count):
seq.append(next(it))
seq = [str(x) for x in seq]
print "try %s: %s..." % (trynum + 1, ", ".join(seq))
| How to generate a predictable shuffling of a sequence without generating the whole sequence in advance? | The following python code describes exactly what I want to achieve for a sequence of arbitrary size (population):
import random
fixed_seed = 1 #generate the same sequence every time with a fixed seed
population = 1000
sample_count = 5 #demonstration number
num_retries = 3 #just enough to show the repeatable behaviour
for trynum in xrange(num_retries):
#generate the fresh/ordered sequence (0->population)...
seq = range(population)
#seed the random number generator the same way every time...
random.seed(fixed_seed)
#shuffle the sequence...
random.shuffle(seq)
#display results for this try...
sample_sequence = [str(x) for x in seq[:sample_count]]
print "try %s: %s..." % (trynum + 1, ", ".join(sample_sequence))
#Sample output...
#try 1: 995, 721, 62, 326, 541...
#try 2: 995, 721, 62, 326, 541...
#try 3: 995, 721, 62, 326, 541...
The problem with that method is that it requires generating the entire
sequence in memory first. This can be a problem for huge populations.
Note that a potentially big advantage of this method is that you can pick off any array position at any time.
Now - If the problem at hand happens to let you set the population size to a power of two
(minus 1), a Linear Feedback Shift Register can be used to get the predictable random sequence. LFSRs are neat, and explained pretty well in the wikipedia article on them.
The python code below demonstrates this (and I did a pile of uniqueness testing to ensure it works as advertised). See the wikipedia article again for an explanation of how the code works (Galois configuration).
TAP_MASKS = { #only one needed, but I included 3 to make the code more useful
10: 0x00000240, #taps at 10, 7
16: 0x0000B400, #taps at 16, 14, 13, 11
32: 0xE0000200, #taps at 32, 31, 30, 10
}
def MaxLengthLFSR(seed, register_length):
"Gets next value from seed in max-length LFSR using Galois configuration."
lsb = seed & 1
next_val = seed >> 1
if lsb == 1:
mask = TAP_MASKS[register_length]
next_val ^= mask
return next_val
reglen = 16 #number of bits in register
population = (2**reglen) - 1 #not used, just showing it
fixed_seed = 1 #seed == startval in this case (could randomize in population)
sample_count = 5 #demonstration number
num_retries = 3 #just enough to show the repeatable behaviour
for trynum in xrange(num_retries):
next_val = fixed_seed
seq = [fixed_seed, ]
for x in xrange(sample_count - 1):
next_val = MaxLengthLFSR(next_val, reglen)
seq.append(next_val)
seq = [str(x) for x in seq]
print "try %s: %s..." % (trynum + 1, ", ".join(seq))
#Sample output...
#try 1: 1, 46080, 23040, 11520, 5760...
#try 2: 1, 46080, 23040, 11520, 5760...
#try 3: 1, 46080, 23040, 11520, 5760...
This is nice because you can have a HUGE population and easily calculate a repeatable non-repeating random number sequence without using a big chunk of memory.
The drawbacks are a) that it is limited to a "shuffling" sequences of size (2**N - 1), and b) that you cannot determine what the value of a particular position in the random sequence is at an arbitrary location. You need to know the value at a particular point and walk the sequence from there.
The latter (b) is mostly ok since most of the time you'll generate the sequence in order, so you just need to remember the last value. The power of 2 limitation (a) is kind of a deal killer,though... depending on the application.
How do you achieve maximum-length-LFSR-like non-repeating results for arbitrary sequence lengths?
As a bonus, it would be nice to have a solution where you are able to know the number at a given sequence position without needing to walk through the sequence to that position.
Note: if you want a good starting set of LFSR tap locations for maximum-length LFSRs (ones that generate the whole register population without repeating once), this link is quite good and has a huge number of tap locations per register size (up to 32 bits, anyway).
Also please note that I've seen many questions closely related to my question and shuffling/LFSR, but none of them exactly relate to what I'm after (predictable shuffle of arbitrary size linear sequence). Or at least as far as I have been able to understand them, anyway.
I've recently been looking into Linear Congruential Generators, which seem promising, but I haven't been able to get them to work yet. Rather than sitting on the question further I'll ask it, and post the answer if I figure it out and they work.
| [
"I've actually written about this before: Secure Permutations with Block Ciphers. In a nutshell:\n\nYes, you can use an LFSR to generate permutations with a length that's a power of 2. You can also use any block cipher. With a block cipher, you can also find the element at index n, or the index for element n.\nTo g... | [
4,
1
] | [] | [] | [
"algorithm",
"lcg",
"python",
"random"
] | stackoverflow_0003910101_algorithm_lcg_python_random.txt |
Q:
sandbox to execute possibly unfriendly python code
Let's say there is a server on the internet that one can send a piece of code to for evaluation. At some point server takes all code that has been submitted, and starts running and evaluating it. However, at some point it will definitely bump into "os.system('rm -rf *')" sent by some evil programmer. Apart from "rm -rf" you could expect people try using the server to send spam or dos someone, or fool around with "while True: pass" kind of things.
Is there a way to coop with such unfriendly/untrusted code? In particular I'm interested in a solution for python. However if you have info for any other language, please share.
A:
If you are not specific to CPython implementation, you should consider looking at PyPy[wiki] for these purposes — this Python dialect allows transparent code sandboxing.
Otherwise, you can provide fake __builtin__ and __builtins__ in the corresponding globals/locals arguments to exec or eval.
Moreover, you can provide dictionary-like object instead of real dictionary and trace what untrusted code does with it's namespace.
Moreover, you can actually trace that code (issuing sys.settrace() inside restricted environment before any other code executed) so you can break execution if something will go bad.
If none of solutions is acceptable, use OS-level sandboxing like chroot, unionfs and standard multiprocess python module to spawn code worker in separate secured process.
A:
It's impossible to provide an absolute solution for this because the definition of 'bad' is pretty hard to nail down.
Is opening and writing to a file bad or good? What if that file is /dev/ram?
You can profile signatures of behavior, or you can try to block anything that might be bad, but you'll never win. Javascript is a pretty good example of this, people run arbitrary javascript code all the time on their computers -- it's supposed to be sandboxed but there's all sorts of security problems and edge conditions that crop up.
I'm not saying don't try, you'll learn a lot from the process.
Many companies have spent millions (Intel just spent billions on McAffee) trying to understand how to detect 'bad code' -- and every day machines running McAffe anti-virus get infected with viruses. Python code isn't any less dangerous than C. You can run system calls, bind to C libraries, etc.
A:
I would seriously consider virtualizing the environment to run this stuff, so that exploits in whatever mechanism you implement can be firewalled one more time by the configuration of the virtual machine.
Number of users and what kind of code you expect to test/run would have considerable influence on choices btw. If they aren't expected to link to files or databases, or run computationally intensive tasks, and you have very low pressure, you could be almost fine by just preventing file access entirely and imposing a time limit on the process before it gets killed and the submission flagged as too expensive or malicious.
If the code you're supposed to test might be any arbitrary Django extension or page, then you're in for a lot of work probably.
A:
You can check pysandbox which does just that, though the VM route is probably safer if you can afford it.
A:
You can try some generic sanbox such as Sydbox or Gentoo's sandbox. They are not Python-specific.
Both can be configured to restrict read/write to some directories. Sydbox can even sandbox sockets.
A:
I think a fix like this is going to be really hard and it reminds me of a lecture I attended about the benefits of programming in a virtual environment.
If you're doing it virtually its cool if they bugger it. It wont solve a while True: pass but rm -rf / won't matter.
A:
Unless I'm mistaken (and I very well might be), this is much of the reason behind the way Google changed Python for the App Engine. You run Python code on their server, but they've removed the ability to write to files. All data is saved in the "nosql" database.
It's not a direct answer to your question, but an example of how this problem has been dealt with in some circumstances.
| sandbox to execute possibly unfriendly python code | Let's say there is a server on the internet that one can send a piece of code to for evaluation. At some point server takes all code that has been submitted, and starts running and evaluating it. However, at some point it will definitely bump into "os.system('rm -rf *')" sent by some evil programmer. Apart from "rm -rf" you could expect people try using the server to send spam or dos someone, or fool around with "while True: pass" kind of things.
Is there a way to coop with such unfriendly/untrusted code? In particular I'm interested in a solution for python. However if you have info for any other language, please share.
| [
"If you are not specific to CPython implementation, you should consider looking at PyPy[wiki] for these purposes — this Python dialect allows transparent code sandboxing.\nOtherwise, you can provide fake __builtin__ and __builtins__ in the corresponding globals/locals arguments to exec or eval.\nMoreover, you can p... | [
6,
2,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"trusted_vs_untrusted"
] | stackoverflow_0003910223_python_trusted_vs_untrusted.txt |
Q:
m2crypto: python 2.7 compatibility and which version of OpenSSL to use?
We've been using M2crypto with Python 2.6 for Windows (32-bit) for some time with great success. We used one of the user contributed setups to install M2crypto in our development environments. We would like to move to Python 2.7, but noticed there are no pre-built Python 2.7 setups for m2crypto.
Questions:
Is M2crypto 0.20.2 compatible with Python 2.7 or should we remain at Python 2.6 if we want to continue to use this library?
Does anyone have a user built setup for installing M2Crypto 0.20.2 in a Python 2.7 environment? (There are no 2.7 contributions on the M2crypto site and google comes up empty as well)
Can we copy our Python 2.6 M2Crypto files (under lib\site-packages\M2Crypto) to the same place in our Python 2.7 setup and avoid a formal installation process?
What version of OpenSLL should we use with M2crypto 0.20.2? I checked the OpenSSL website and there appear 2 versions of OpenSSL to choose from: 0.9.8 and 1.0.0a.
Thank you,
Malcolm
A:
Yes, it's compatible with Python 2.7, so you can freely upgrade if you have not already.
Yes, here you have bdist_wininst, bdist_egg and bdist for M2Crypto 20.2 built for Python 2.7 with MSVS2008 by me, hope it will fit your needs.
No, you will get import error, as .pyd file (which is actually DLL) has python26.dll in it's import table, so this will not work. Of course, you can hack it and replace python26 with python27, but that's too dirt and gives you no guarantee it will work all the time.
Version I uploaded for you works fine with OpenSSL 0.9.8o, haven't tested it with 1.0.0.
| m2crypto: python 2.7 compatibility and which version of OpenSSL to use? | We've been using M2crypto with Python 2.6 for Windows (32-bit) for some time with great success. We used one of the user contributed setups to install M2crypto in our development environments. We would like to move to Python 2.7, but noticed there are no pre-built Python 2.7 setups for m2crypto.
Questions:
Is M2crypto 0.20.2 compatible with Python 2.7 or should we remain at Python 2.6 if we want to continue to use this library?
Does anyone have a user built setup for installing M2Crypto 0.20.2 in a Python 2.7 environment? (There are no 2.7 contributions on the M2crypto site and google comes up empty as well)
Can we copy our Python 2.6 M2Crypto files (under lib\site-packages\M2Crypto) to the same place in our Python 2.7 setup and avoid a formal installation process?
What version of OpenSLL should we use with M2crypto 0.20.2? I checked the OpenSSL website and there appear 2 versions of OpenSSL to choose from: 0.9.8 and 1.0.0a.
Thank you,
Malcolm
| [
"Yes, it's compatible with Python 2.7, so you can freely upgrade if you have not already.\nYes, here you have bdist_wininst, bdist_egg and bdist for M2Crypto 20.2 built for Python 2.7 with MSVS2008 by me, hope it will fit your needs.\nNo, you will get import error, as .pyd file (which is actually DLL) has python26.... | [
3
] | [] | [] | [
"m2crypto",
"openssl",
"python",
"python_2.7"
] | stackoverflow_0003857450_m2crypto_openssl_python_python_2.7.txt |
Q:
Pass data between objects in python
I'm new to python and I'm not sure how to pass data between objects. Below is a tabbed program using python and wxwidgets. How would I be able to access the maintxt instance from the GetText method since their in different classes?
Thanks.
........
#!/usr/bin/env python
import wx
class PageText(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.maintxt = wx.TextCtrl(self, style=wx.TE_MULTILINE, pos=(0, 40), size=(850,320))
self.Show(True)
class PageList(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.bPutText = wx.Button(self, id=-1, label='Put Text', pos=(855, 40), size=(75, 30))
self.bPutText.Bind(wx.EVT_LEFT_DOWN, self.GetText)
def GetText(self, event):
# Write text into maintxt
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="ADMIN")
p = wx.Panel(self)
nb = wx.Notebook(p)
vPageText = PageText(nb)
vPageList = PageList(nb)
nb.AddPage(vPageText, "Edit Text")
nb.AddPage(vPageList, "Book List")
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
p.SetSizer(sizer)
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()
A:
It sounds like you might be mixing logic with presentation. You should perhaps have a network of model classes that describe the behaviors of your domain (pages?) and then pass instances of those classes to the initializers of your presentation classes, so they know which models they are representing.
More about this design: http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller
| Pass data between objects in python | I'm new to python and I'm not sure how to pass data between objects. Below is a tabbed program using python and wxwidgets. How would I be able to access the maintxt instance from the GetText method since their in different classes?
Thanks.
........
#!/usr/bin/env python
import wx
class PageText(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.maintxt = wx.TextCtrl(self, style=wx.TE_MULTILINE, pos=(0, 40), size=(850,320))
self.Show(True)
class PageList(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.bPutText = wx.Button(self, id=-1, label='Put Text', pos=(855, 40), size=(75, 30))
self.bPutText.Bind(wx.EVT_LEFT_DOWN, self.GetText)
def GetText(self, event):
# Write text into maintxt
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="ADMIN")
p = wx.Panel(self)
nb = wx.Notebook(p)
vPageText = PageText(nb)
vPageList = PageList(nb)
nb.AddPage(vPageText, "Edit Text")
nb.AddPage(vPageList, "Book List")
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
p.SetSizer(sizer)
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()
| [
"It sounds like you might be mixing logic with presentation. You should perhaps have a network of model classes that describe the behaviors of your domain (pages?) and then pass instances of those classes to the initializers of your presentation classes, so they know which models they are representing.\nMore about... | [
4
] | [] | [] | [
"class",
"pass_by_reference",
"python"
] | stackoverflow_0003911259_class_pass_by_reference_python.txt |
Q:
Python, format this list
I've got a list like
[(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
I want to make it looks like
[('1',' ', '2', '8'), ('2', ' ', '3', '7', '8', '9'), ('3', " ", '2', '5', '6', '7', '7', '9')]
How can I code this loop? Really tried times, and nothing came up. Please help~~
A:
Step 1. Convert the list to a dictionary. Each element is a list of values with a common key. (Hint: The key is the first value of each pair)
Step 2. Now format each dictionary as key, space, value list.
A:
Not exactly what you asked for, but maybe easier to work with?
>>> from itertools import groupby
>>> L = [(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
>>> for key, group in groupby(L, lambda x: x[0]):
... print key, list(group)
...
1 [(1, 2), (1, 8)]
2 [(2, 3), (2, 7), (2, 8), (2, 9)]
3 [(3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
Link to documentation.
Edit:
I suppose something like this is more what you're asking for:
>>> d = {}
>>> for key, group in groupby(L, lambda x: x[0]):
... d[key] = [i[1] for i in group]
...
>>> d
{1: [2, 8], 2: [3, 7, 8, 9], 3: [1, 2, 5, 6, 7, 7, 9]}
If you absolutely want the key to be a string, you can code it this way:
d[str(key)] = [i[1] for i in group]
A:
from collections import defaultdict
s = [
(1,2),(1,8),
(2,3),(2,7),(2,8),(2,9),
(3,1),(3,2),(3,5),(3,6),(3,7),(3,7),(3,9)
]
D = defaultdict(list)
for a,b in s:
D[a].append(b)
L = []
for k in sorted(D.keys()):
e = [str(k),'']
e.extend(map(str,D[k]))
L.append(tuple(e))
print L
Output:
[('1', '', '2', '8'), ('2', '', '3', '7', '8', '9'), ('3', '', '1', '2', '5', '6', '7', '7', '9')]
You've got to explain how it works to your teacher ;^)
A:
a = [(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
x1=None # here we keep track of the last x we saw
ys=None # here we keep track of all ys we've seen for this x1
result = []
for x,y in a:
if x != x1: # this is an x we haven't seen before
if ys: # do we have results for the last x?
result.append( ys )
ys = [ x, '', y ] # initialize the next set of results
x1 = x
else:
ys.append( y ) # add this to the results we are buliding
if ys:
result.append( ys ) # add the last set of results
print result
| Python, format this list | I've got a list like
[(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
I want to make it looks like
[('1',' ', '2', '8'), ('2', ' ', '3', '7', '8', '9'), ('3', " ", '2', '5', '6', '7', '7', '9')]
How can I code this loop? Really tried times, and nothing came up. Please help~~
| [
"Step 1. Convert the list to a dictionary. Each element is a list of values with a common key. (Hint: The key is the first value of each pair)\nStep 2. Now format each dictionary as key, space, value list.\n",
"Not exactly what you asked for, but maybe easier to work with?\n>>> from itertools import groupby\n... | [
2,
2,
2,
0
] | [] | [] | [
"formatting",
"list",
"python"
] | stackoverflow_0003911319_formatting_list_python.txt |
Q:
Looping over a Python / IronPython Object Methods
What is the proper way to loop over a Python object's methods and call them?
Given the object:
class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
A:
You can use the inspect module to get class (or instance) members:
>>> class C(object):
... a = 'blah'
... def b(self):
... pass
...
...
>>> c = C()
>>> inspect.getmembers(c, inspect.ismethod)
[('b', <bound method C.b of <__main__.C object at 0x100498250>>)]
getmembers() returns a list of tuples, where each tuple is (name, member). The second argument to getmembers() is the predicate, which filters the return list (in this case, returning only method objects)
A:
Methods vs. functions and other types of callables...
(To address the issue in the comments in Unknown's post.)
First, it should be noted that, in addition to user-defined methods, there are built-in methods, and a built-in method is, as the doc at http://docs.python.org/reference/datamodel.html says, "really a different disguise of a built-in function" (which is a wrapper around a C function.)
As for user-defined methods, as Unknown's cited quote says:
A user-defined method object combines
a class, a class instance (or None)
and any callable object (normally a
user-defined function).
But this does not mean that "anything that defines __call__ and is attached to an object is a method." A method is a callable, but a callable is not necessarily a method. User-defined methods are wrappers around what the quote says.
Hopefully this output (from Python 2.5.2 which I have handy) will show the distinction:
IDLE 1.2.2
>>> class A(object):
x = 7
>>> A # show the class object
<class '__main__.A'>
>>> a = A()
>>> a # show the instance
<__main__.A object at 0x021AFBF0>
>>> def test_func(self):
print self.x
>>> type(test_func) # what type is it?
<type 'function'>
>>> dir(test_func) # what does it have?
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__',
'__getattribute__', '__hash__', '__init__', '__module__', '__name__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
'func_doc', 'func_globals', 'func_name']
>>> # But now let's put test_func on the class...
>>> A.test = test_func
>>> type(A.test) # What type does this show?
<type 'instancemethod'>
>>> dir(A.test) # And what does it have?
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__',
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class',
'im_func', 'im_self']
>>> # See, we just got a wrapper, and the function is in 'im_func'...
>>> getattr(A.test, 'im_func')
<function test_func at 0x0219F4B0>
>>> # Now to show bound vs. unbound methods...
>>> getattr(a.test, 'im_self') # Accessing it via the instance
<__main__.A object at 0x021AFBF0>
>>> # The instance is itself 'im_self'
>>> a.test()
7
>>> getattr(A.test, 'im_self') # Accessing it via the class returns None...
>>> print getattr(A.test, 'im_self')
None
>>> # It's unbound when accessed that way, so there's no instance in there
>>> # Which is why the following fails...
>>> A.test()
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
A.test()
TypeError: unbound method test_func() must be called with A instance as
first argument (got nothing instead)
>>>
And - editing to add the following additional output, which is also relevant...
>>> class B(object):
pass
>>> b = B()
>>> b.test = test_func # Putting the function on the instance, not class
>>> type(b.test)
<type 'function'>
>>>
I wont add more output, but you could also make a class an attribute of another class or instance, and, even though classes are callable, you would not get a method. Methods are implemented using non-data descriptors, so look up descriptors if you want more info on how they work.
A:
This code snippet will call anything it will find in obj and store results in mapping, where key is attribute name — dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))
| Looping over a Python / IronPython Object Methods | What is the proper way to loop over a Python object's methods and call them?
Given the object:
class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
| [
"You can use the inspect module to get class (or instance) members:\n>>> class C(object):\n... a = 'blah'\n... def b(self):\n... pass\n... \n...\n>>> c = C()\n>>> inspect.getmembers(c, inspect.ismethod)\n[('b', <bound method C.b of <__main__.C object at 0x100498250>>)]\n\ngetmembers() returns a ... | [
10,
4,
0
] | [
"Edit\nDaniel, you are wrong.\nhttp://docs.python.org/reference/datamodel.html\n\nUser-defined methods\nA user-defined method object combines a class, a class instance (or\nNone) and any callable object (normally a user-defined function).\n\nTherefore, anything that defines __call__ and is attached to an object is ... | [
-1
] | [
"introspection",
"ironpython",
"python",
"python_datamodel",
"reflection"
] | stackoverflow_0000928990_introspection_ironpython_python_python_datamodel_reflection.txt |
Q:
How does CherryPy caching work?
I recently discovered that page object attributes in CherryPy are persistent between requests (and between clients). So I'm wondering, would it make sense to store page output in such an attribute? Like this:
class Page:
def default(self, pagenumber):
if pagenumber not in self.validpages:
return 'Page number not found'
try:
html = self.pageoutput[pagenumber]
except KeyError:
html = self.formatter(self.dbcall(pagenumber))
return html
default.exposed = True
def formatter(self, data):
html = # Formatting code here
return html
def dbcall(self, pagenumber):
data = # Database lookup code here
return data
I know CherryPy caches GET requests by default. In my tests, when an object attribute was part of the output and that attribute changed, CherryPy served the attribute's new value. Does that mean the output was only partially cached?
To me this would be useful as long as you updated self.pageoutput every time you changed your database. The only difficulty I could imagine is if I wanted to display user-specific information. What do you think?
A:
CherryPy does not cache GET requests by default; you have to explicitly turn on the caching tool as described in that documentation.
To answer your first question, yes, it's perfectly valid to store things like "pageoutput" that do not change between calls. However, there are a couple of caveats:
HTTP caching is far better than what you can write on your own. So prefer that for whole responses.
Therefore, use ad-hoc caching for parts of responses, such as templates and banners and such.
Be very careful to design your storage to be safely concurrent. See effbot's writeup on that subject for a start. In general, try to generate and store such values at application startup if feasible, instead of during a request; if you write such data in the main thread only at startup, it should be safely readable by multiple threads for each request. If you need such data to change as the application state progresses, you probably want to use a database or some other mechanism that has had hundreds of man-years of work to make it safely concurrent.
| How does CherryPy caching work? | I recently discovered that page object attributes in CherryPy are persistent between requests (and between clients). So I'm wondering, would it make sense to store page output in such an attribute? Like this:
class Page:
def default(self, pagenumber):
if pagenumber not in self.validpages:
return 'Page number not found'
try:
html = self.pageoutput[pagenumber]
except KeyError:
html = self.formatter(self.dbcall(pagenumber))
return html
default.exposed = True
def formatter(self, data):
html = # Formatting code here
return html
def dbcall(self, pagenumber):
data = # Database lookup code here
return data
I know CherryPy caches GET requests by default. In my tests, when an object attribute was part of the output and that attribute changed, CherryPy served the attribute's new value. Does that mean the output was only partially cached?
To me this would be useful as long as you updated self.pageoutput every time you changed your database. The only difficulty I could imagine is if I wanted to display user-specific information. What do you think?
| [
"CherryPy does not cache GET requests by default; you have to explicitly turn on the caching tool as described in that documentation.\nTo answer your first question, yes, it's perfectly valid to store things like \"pageoutput\" that do not change between calls. However, there are a couple of caveats:\n\nHTTP cachin... | [
4
] | [] | [] | [
"caching",
"cherrypy",
"get",
"python"
] | stackoverflow_0003908577_caching_cherrypy_get_python.txt |
Q:
What have i done wrong? (python help)
The question i'm working on asks me to "write an expression whose value is the concatenation of the three str values associated with name1 , name2 , and name3" , separated by commas."
"So if name1 , name2 , and name3 , were (respectively) "Neville", "Dean", and "Seamus", your expression's value would be "Neville,Dean,Seamus". "
The answer that i submitted is "name1,name2,name3" but when i click "submit" the message informs of a logical error within my code and that my expression didn't return the correct value. What have i done wrong?
A:
Homework? Did you submit the result of the expression, or the expression itself?
",".join([name1, name2, name3])
Or whatever you used?
Edit: You mention that you submitted ("name1", "name2", "name3") - which would not return the concatenated names - but rather those stings. If you wanted to do it like this (a little less elegant then the version I put above) you could try:
name1 + "," + name2 + "," + name3
The difference being the quotations (") around the names - are stopping you from using the variables provided.
Edit2: This is how I understand the question you were asked. They want you to submit to them, an expression that will return the values assigned to the name1, name2 and name3 variables (whatever they may be) - There are two examples of such expressions above - which concatenate the three name variables, and add a comma between them - have you tried submitting either of the examples above?
| What have i done wrong? (python help) | The question i'm working on asks me to "write an expression whose value is the concatenation of the three str values associated with name1 , name2 , and name3" , separated by commas."
"So if name1 , name2 , and name3 , were (respectively) "Neville", "Dean", and "Seamus", your expression's value would be "Neville,Dean,Seamus". "
The answer that i submitted is "name1,name2,name3" but when i click "submit" the message informs of a logical error within my code and that my expression didn't return the correct value. What have i done wrong?
| [
"Homework? Did you submit the result of the expression, or the expression itself?\n\",\".join([name1, name2, name3])\nOr whatever you used?\nEdit: You mention that you submitted (\"name1\", \"name2\", \"name3\") - which would not return the concatenated names - but rather those stings. If you wanted to do it like ... | [
3
] | [] | [] | [
"python",
"string_concatenation"
] | stackoverflow_0003911519_python_string_concatenation.txt |
Q:
Python: What is the recommended way to set configuration settings for a module when you import it?
I've seen people use monkey-patching to set options on a module, for example:
import mymodule
mymodule.default_img = "/my/file.png"
mymodule.view_default_img()
And Django, for example, has settings.py for the entire Django app, and it always grates on me a little.
What are the other ways to manage configuration settings on a module? What's recommended? It seems like there's often no nice way to setup module-level configuration.
Obviously, completely avoiding configuration is by far the most preferable, and it's usually better to use classes, or pass in the argument to a function. But sometimes you can't avoid having settings of some sort, and sometimes it really does make sense to have global module-wide settings just for convenience (for example, Django's template system -- having to specify the base path for every template would be a nightmare, definitely not good DRY code).
A:
One option is the ConfigParser module. You could have the settings in a non-python config file and have each module read its settings out of that. Another option is to have a config method in each module that the client code can pass it's arguments too.
# foo.py
setting1 = 0
setting2 = 'foo'
def configure(config1, config2):
global setting1, setting2
setting1 = config1
setting2 = config2
Then in the importing module,
import foo
foo.configure(42, 'bar')
Personally, I think that the best way to do it is with the settings file like django.
| Python: What is the recommended way to set configuration settings for a module when you import it? | I've seen people use monkey-patching to set options on a module, for example:
import mymodule
mymodule.default_img = "/my/file.png"
mymodule.view_default_img()
And Django, for example, has settings.py for the entire Django app, and it always grates on me a little.
What are the other ways to manage configuration settings on a module? What's recommended? It seems like there's often no nice way to setup module-level configuration.
Obviously, completely avoiding configuration is by far the most preferable, and it's usually better to use classes, or pass in the argument to a function. But sometimes you can't avoid having settings of some sort, and sometimes it really does make sense to have global module-wide settings just for convenience (for example, Django's template system -- having to specify the base path for every template would be a nightmare, definitely not good DRY code).
| [
"One option is the ConfigParser module. You could have the settings in a non-python config file and have each module read its settings out of that. Another option is to have a config method in each module that the client code can pass it's arguments too.\n# foo.py\nsetting1 = 0\nsetting2 = 'foo'\n\ndef configure(co... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003911539_python.txt |
Q:
Can someone please explain to me
.. the difference between the = and the == signs in Python? i.e provide examples when each is used so there's no confusion between the two?
A:
= is used to assign variables ie number = 30 - the "number" variable now holds the number 30.
== is used as a boolean operator to check whether variables are equal to each other ie 1 == 1 would give true and 1 == 2 would return false
A:
= is assignment, == is equality.
a = 5 # assigns the variable a to 5
a == 5 # returns true
a == 4 # returns false
a = 4 # a is now 4
a == 4 # returns true
A:
= is assignment, you would use it to give a value to a variable.
str = "hello" assigns "hello" to str, so that if you were to get the value of str, it would be a hello.
== is equality comparison, you use it to compare two values.
if str == "hello":
print "equal"
else:
print "not equal"
In that code you want to see if the value of str is equal to the string "hello", and if we assigned it as above, this would result in "equal" being printed.
A:
"==" is checking for equality. "=" is for assignment of values. eg v="100" Then to check whether v is 100, v==100
| Can someone please explain to me | .. the difference between the = and the == signs in Python? i.e provide examples when each is used so there's no confusion between the two?
| [
"= is used to assign variables ie number = 30 - the \"number\" variable now holds the number 30.\n== is used as a boolean operator to check whether variables are equal to each other ie 1 == 1 would give true and 1 == 2 would return false\n",
"= is assignment, == is equality.\na = 5 # assigns the variable a to 5\... | [
3,
1,
0,
0
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0003911726_operators_python.txt |
Q:
python - nested try/except question
try:
for i in list:
try:
#python code...
except Exception,e:
#error handler
except Exception, e:
#error handler
If in the nested try/except it errors out, does the loop continue running?
A:
Yes, it does, since you caught the exception. Although if you just have a comment there and not a real line of code, I think Python may complain. (I haven't written Python code in a while.)
A:
Aside from the typo for "cexcept" in the inner except, the loop should continue. Actually, the parent try/except can not be broken only by that for, but I'm sure this is just a simple example of the actual code.
| python - nested try/except question | try:
for i in list:
try:
#python code...
except Exception,e:
#error handler
except Exception, e:
#error handler
If in the nested try/except it errors out, does the loop continue running?
| [
"Yes, it does, since you caught the exception. Although if you just have a comment there and not a real line of code, I think Python may complain. (I haven't written Python code in a while.)\n",
"Aside from the typo for \"cexcept\" in the inner except, the loop should continue. Actually, the parent try/except can... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003911823_python.txt |
Q:
How to return the maximum element of a slice of a list
I am trying to simplify this function at his maximum, how can I do?
def eleMax(items, start=0, end=None):
if end is None:
end = len(items)
return max(items[start:end])
I thought of
def eleMax(items, start=0, end=-1):
return max(items[start:end])
But the last element is deleted from the list.
A:
You can just remove these two lines:
if end is None:
end = len(items)
The function will work exactly the same:
>>> a=[5,4,3,2,1]
>>> def eleMax(items, start=0, end=None):
... return max(items[start:end])
...
>>> eleMax(a,2) # a[2:] == [3,2,1]
3
A:
Just use max(items).
Python ranges are 'half-open'. When you slice a list in Python with [start:end] syntax, the start is included and the end is omitted.
A:
def eleMax(items, start=None, end=None):
return max(items[slice(start, end)])
A:
When operating over large lists or many calls to this you can avoid the overhead of the slice creating a new list and copying the pointers.
http://docs.python.org/library/itertools.html#itertools.islice
Itertools contains islice which allows for iterating over the list in place without actually returning a new list for the slice.
from itertools import islice
def eleMax(items, start=None, end=None):
return max(itertools.islice(items, start, end))
One current limitation is that negative values are not allowed for start, end, step.
| How to return the maximum element of a slice of a list | I am trying to simplify this function at his maximum, how can I do?
def eleMax(items, start=0, end=None):
if end is None:
end = len(items)
return max(items[start:end])
I thought of
def eleMax(items, start=0, end=-1):
return max(items[start:end])
But the last element is deleted from the list.
| [
"You can just remove these two lines:\nif end is None:\n end = len(items)\n\nThe function will work exactly the same:\n>>> a=[5,4,3,2,1]\n>>> def eleMax(items, start=0, end=None):\n... return max(items[start:end])\n...\n>>> eleMax(a,2) # a[2:] == [3,2,1]\n3\n\n",
"Just use max(items).\nPython ranges are ... | [
4,
2,
2,
1
] | [] | [] | [
"max",
"python",
"slice"
] | stackoverflow_0003892957_max_python_slice.txt |
Q:
Set cellrenderertext foreground color when a row is highlighted
When I have a gtk.CellRendererText, I can associate its foreground color with one of the tree store's columns, and set the foreground-set attribute to True, to change the color of the text in that column. However, when the row with the colored column is selected, its color disappears, and is the same as any selected cell's color. How do I change the color when it's selected?
A:
I've had the same problem and, after trying different alternatives, using the markup property instead of the text property solved the problem. Please find below and example that works in Ubuntu Maverick:
#!/usr/bin/python
import gtk
class Application(object):
def __init__(self):
window = gtk.Window()
model = gtk.TreeStore(str)
model.append(None, row=('Normal row',))
model.append(None, row=('<span foreground="red">Red row</span>',))
treeview = gtk.TreeView(model)
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('Column', renderer, markup=0)
treeview.append_column(column)
scrolled_window = gtk.ScrolledWindow()
scrolled_window.add(treeview)
window.add(scrolled_window)
window.connect('destroy', lambda w: gtk.main_quit())
window.show_all()
def run(self):
gtk.main()
if __name__ == '__main__':
Application().run()
In a more complex treeview with the multiple columns that I'm working on, the markup property doesn't seem to work when the row isn't selected. Anyway, usage of both markup and foreground properties at the same time seems to work fine.
| Set cellrenderertext foreground color when a row is highlighted | When I have a gtk.CellRendererText, I can associate its foreground color with one of the tree store's columns, and set the foreground-set attribute to True, to change the color of the text in that column. However, when the row with the colored column is selected, its color disappears, and is the same as any selected cell's color. How do I change the color when it's selected?
| [
"I've had the same problem and, after trying different alternatives, using the markup property instead of the text property solved the problem. Please find below and example that works in Ubuntu Maverick:\n#!/usr/bin/python \nimport gtk\n\n\nclass Application(object):\n def __init__... | [
7
] | [] | [] | [
"cellrenderer",
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003629386_cellrenderer_gtk_gtktreeview_pygtk_python.txt |
Q:
Issue happens when installing Django on Windows 7
I've got an issue when installing Django.
The official guide says open cmd with administrator privileges and run "setup.py install"
I did this but then the system default python editor came out, I don't know how to do anymore, please help me~
A:
It is very likely that the py extension is linked with the editor rather than the Python interpreter.
Right-click on a py file and click "Open with" then select the default program and choose 'C:...\Python2x\python.exe'
That should fix the pb
| Issue happens when installing Django on Windows 7 | I've got an issue when installing Django.
The official guide says open cmd with administrator privileges and run "setup.py install"
I did this but then the system default python editor came out, I don't know how to do anymore, please help me~
| [
"It is very likely that the py extension is linked with the editor rather than the Python interpreter.\nRight-click on a py file and click \"Open with\" then select the default program and choose 'C:...\\Python2x\\python.exe'\nThat should fix the pb\n"
] | [
2
] | [] | [] | [
"django",
"installation",
"python"
] | stackoverflow_0003912579_django_installation_python.txt |
Q:
Apache Can't Access Django Applications
so here's the setting:
The whole site is working fine if I remove the application (whose name
is myapp) in the INSTALLED_APPS section in the settings file I added WSGIPythonHome in apache2.conf
I can successfully access the apps via the the interactive python shell in Django (python manage.py shell). I can create, update and delete data.
I am using the standard Apache 2 setup for Ubuntu 10.04 Lucid Lynx(sites-enabled, mods-enabled, apache2.conf, etc)
I am running a virtualenv located in /home/ygamretuta/dev/myproject
My django project is located in /home/ygamretuta/dev/site1
error Log file says this (last 2 lines):
File "/home/ygamretuta/dev/myproject/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
TemplateSyntaxError: Caught ImportError while rendering: No module named myapp
my django.wsgi contains this:
import os, sys
sys.path.append('/home/ygamretuta/dev')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
my virtual host file for site1.com (contained in the sites-available folder) contains this (stripped of other details):
WSGIDaemonProcess ygamretuta processes=2 maximum-requests=500 threads=1
WSGIProcessGroup ygamretuta
WSGIScriptAlias / /home/ygamretuta/dev/site1/apache/django.wsgi
What could I have missed? I am getting e 500 Internal Server Error if the custom apps (the ones I made with manage.py startapp) are not commented out
A:
Append /home/ygamretuta/dev/site1 to sys.path.
| Apache Can't Access Django Applications | so here's the setting:
The whole site is working fine if I remove the application (whose name
is myapp) in the INSTALLED_APPS section in the settings file I added WSGIPythonHome in apache2.conf
I can successfully access the apps via the the interactive python shell in Django (python manage.py shell). I can create, update and delete data.
I am using the standard Apache 2 setup for Ubuntu 10.04 Lucid Lynx(sites-enabled, mods-enabled, apache2.conf, etc)
I am running a virtualenv located in /home/ygamretuta/dev/myproject
My django project is located in /home/ygamretuta/dev/site1
error Log file says this (last 2 lines):
File "/home/ygamretuta/dev/myproject/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
TemplateSyntaxError: Caught ImportError while rendering: No module named myapp
my django.wsgi contains this:
import os, sys
sys.path.append('/home/ygamretuta/dev')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
my virtual host file for site1.com (contained in the sites-available folder) contains this (stripped of other details):
WSGIDaemonProcess ygamretuta processes=2 maximum-requests=500 threads=1
WSGIProcessGroup ygamretuta
WSGIScriptAlias / /home/ygamretuta/dev/site1/apache/django.wsgi
What could I have missed? I am getting e 500 Internal Server Error if the custom apps (the ones I made with manage.py startapp) are not commented out
| [
"Append /home/ygamretuta/dev/site1 to sys.path.\n"
] | [
6
] | [] | [] | [
"django",
"mod_wsgi",
"python",
"virtualenv"
] | stackoverflow_0003912670_django_mod_wsgi_python_virtualenv.txt |
Q:
Python Pyrad dictionary error
I setup some RADIUS backend to allow AD authentication via the 'admin' of django. Alltough i got a problem with some dictionaries, i really don't know what i'm doing wrong. This is the error i got:
IOError at /admin/
Errno 2] No such file or directory: '/home/pl/dictionary.compat'
I installed pyrad, so it should be there and i've got a 'dic't file in the following style (/home/pl/dict):
#
# Version $Id: dictionary,v 1.1.1.1 2002/10/11 12:25:39 wichert Exp $
.....
$INCLUDE dictionary.compat # compability issues
$INCLUDE dictionary.acc
$INCLUDE dictionary.ascend
$INCLUDE dictionary.bay
....
The code i use in the RADIUS backend:
srv = Client(server=settings.RADIUS_SERVER,
secret=settings.RADIUS_SECRET,
dict=Dictionary("/home/pl/dict"))
Any ideas?
A:
The $INCLUDE directive in the configuration files is intended to add definitions from another dictionary file. Unless the extra dictionary files are found, the dictionary object cannot be created.
My advice is:
- if you don't have the extra dictionary files: comment out/remove the $INCLUDE lines
- if you have the extra dictionary files: copy them to the right location
| Python Pyrad dictionary error | I setup some RADIUS backend to allow AD authentication via the 'admin' of django. Alltough i got a problem with some dictionaries, i really don't know what i'm doing wrong. This is the error i got:
IOError at /admin/
Errno 2] No such file or directory: '/home/pl/dictionary.compat'
I installed pyrad, so it should be there and i've got a 'dic't file in the following style (/home/pl/dict):
#
# Version $Id: dictionary,v 1.1.1.1 2002/10/11 12:25:39 wichert Exp $
.....
$INCLUDE dictionary.compat # compability issues
$INCLUDE dictionary.acc
$INCLUDE dictionary.ascend
$INCLUDE dictionary.bay
....
The code i use in the RADIUS backend:
srv = Client(server=settings.RADIUS_SERVER,
secret=settings.RADIUS_SECRET,
dict=Dictionary("/home/pl/dict"))
Any ideas?
| [
"The $INCLUDE directive in the configuration files is intended to add definitions from another dictionary file. Unless the extra dictionary files are found, the dictionary object cannot be created.\nMy advice is:\n- if you don't have the extra dictionary files: comment out/remove the $INCLUDE lines \n- if you have ... | [
0
] | [] | [] | [
"python",
"radius"
] | stackoverflow_0003912740_python_radius.txt |
Q:
Get filename when using urllib.urlopen
I'm using urllib.urlopen to read a file from a URL. What is the best way to get the filename? Do servers always return the Content-Disposition header?
Thanks.
A:
It's an optional header, so no. See if it exists, and if not then fall back to checking the URL.
| Get filename when using urllib.urlopen | I'm using urllib.urlopen to read a file from a URL. What is the best way to get the filename? Do servers always return the Content-Disposition header?
Thanks.
| [
"It's an optional header, so no. See if it exists, and if not then fall back to checking the URL.\n"
] | [
1
] | [] | [] | [
"python",
"urllib",
"urlopen"
] | stackoverflow_0003912910_python_urllib_urlopen.txt |
Q:
Function local name binding from an outer scope
I need a way to "inject" names into a function from an outer code block, so they are accessible locally and they don't need to be specifically handled by the function's code (defined as function parameters, loaded from *args etc.)
The simplified scenario: providing a framework within which the users are able to define (with as little syntax as possible) custom functions to manipulate other objects of the framework (which are not necessarily global).
Ideally, the user defines
def user_func():
Mouse.eat(Cheese)
if Cat.find(Mouse):
Cat.happy += 1
Here Cat, Mouse and Cheese are framework objects that, for good reasons, cannot be bounded to the global namespace.
I want to write a wrapper for this function to behave like this:
def framework_wrap(user_func):
# this is a framework internal and has name bindings to Cat, Mouse and Cheese
def f():
inject(user_func, {'Cat': Cat, 'Mouse': Mouse, 'Cheese': Cheese})
user_func()
return f
Then this wrapper could be applied to all user-defined functions (as a decorator, by the user himself or automatically, although I plan to use a metaclass).
@framework_wrap
def user_func():
I am aware of the Python 3's nonlocal keyword, but I still consider ugly (from the framework's user perspective) to add an additional line:
nonlocal Cat, Mouse, Cheese
and to worry about adding every object he needs to this line.
Any suggestion is greatly appreciated.
A:
The more I mess around with the stack, the more I wish I hadn't. Don't hack globals to do what you want. Hack bytecode instead. There's two ways that I can think of to do this.
1) Add cells wrapping the references that you want into f.func_closure. You have to reassemble the bytecode of the function to use LOAD_DEREF instead of LOAD_GLOBAL and generate a cell for each value. You then pass a tuple of the cells and the new code object to types.FunctionType and get a function with the appropriate bindings. Different copies of the function can have different local bindings so it should be as thread safe as you want to make it.
2) Add arguments for your new locals at the end of the functions argument list. Replace appropriate occurrences of LOAD_GLOBAL with LOAD_FAST. Then construct a new function by using types.FunctionType and passing in the new code object and a tuple of the bindings that you want as the default option. This is limited in the sense that python limits function arguments to 255 and it can't be used on functions that use variable arguments. None the less it struck me as the more challenging of the two so that's the one that I implemented (plus there's other stuff that can be done with this one). Again, you can either make different copies of the function with different bindings or call the function with the bindings that you want from each call location. So it too can be as thread safe as you want to make it.
import types
import opcode
# Opcode constants used for comparison and replacecment
LOAD_FAST = opcode.opmap['LOAD_FAST']
LOAD_GLOBAL = opcode.opmap['LOAD_GLOBAL']
STORE_FAST = opcode.opmap['STORE_FAST']
DEBUGGING = True
def append_arguments(code_obj, new_locals):
co_varnames = code_obj.co_varnames # Old locals
co_names = code_obj.co_names # Old globals
co_argcount = code_obj.co_argcount # Argument count
co_code = code_obj.co_code # The actual bytecode as a string
# Make one pass over the bytecode to identify names that should be
# left in code_obj.co_names.
not_removed = set(opcode.hasname) - set([LOAD_GLOBAL])
saved_names = set()
for inst in instructions(co_code):
if inst[0] in not_removed:
saved_names.add(co_names[inst[1]])
# Build co_names for the new code object. This should consist of
# globals that were only accessed via LOAD_GLOBAL
names = tuple(name for name in co_names
if name not in set(new_locals) - saved_names)
# Build a dictionary that maps the indices of the entries in co_names
# to their entry in the new co_names
name_translations = dict((co_names.index(name), i)
for i, name in enumerate(names))
# Build co_varnames for the new code object. This should consist of
# the entirety of co_varnames with new_locals spliced in after the
# arguments
new_locals_len = len(new_locals)
varnames = (co_varnames[:co_argcount] + new_locals +
co_varnames[co_argcount:])
# Build the dictionary that maps indices of entries in the old co_varnames
# to their indices in the new co_varnames
range1, range2 = xrange(co_argcount), xrange(co_argcount, len(co_varnames))
varname_translations = dict((i, i) for i in range1)
varname_translations.update((i, i + new_locals_len) for i in range2)
# Build the dictionary that maps indices of deleted entries of co_names
# to their indices in the new co_varnames
names_to_varnames = dict((co_names.index(name), varnames.index(name))
for name in new_locals)
if DEBUGGING:
print "injecting: {0}".format(new_locals)
print "names: {0} -> {1}".format(co_names, names)
print "varnames: {0} -> {1}".format(co_varnames, varnames)
print "names_to_varnames: {0}".format(names_to_varnames)
print "varname_translations: {0}".format(varname_translations)
print "name_translations: {0}".format(name_translations)
# Now we modify the actual bytecode
modified = []
for inst in instructions(code_obj.co_code):
# If the instruction is a LOAD_GLOBAL, we have to check to see if
# it's one of the globals that we are replacing. Either way,
# update its arg using the appropriate dict.
if inst[0] == LOAD_GLOBAL:
print "LOAD_GLOBAL: {0}".format(inst[1])
if inst[1] in names_to_varnames:
print "replacing with {0}: ".format(names_to_varnames[inst[1]])
inst[0] = LOAD_FAST
inst[1] = names_to_varnames[inst[1]]
elif inst[1] in name_translations:
inst[1] = name_translations[inst[1]]
else:
raise ValueError("a name was lost in translation")
# If it accesses co_varnames or co_names then update its argument.
elif inst[0] in opcode.haslocal:
inst[1] = varname_translations[inst[1]]
elif inst[0] in opcode.hasname:
inst[1] = name_translations[inst[1]]
modified.extend(write_instruction(inst))
code = ''.join(modified)
# Done modifying codestring - make the code object
return types.CodeType(co_argcount + new_locals_len,
code_obj.co_nlocals + new_locals_len,
code_obj.co_stacksize,
code_obj.co_flags,
code,
code_obj.co_consts,
names,
varnames,
code_obj.co_filename,
code_obj.co_name,
code_obj.co_firstlineno,
code_obj.co_lnotab)
def instructions(code):
code = map(ord, code)
i, L = 0, len(code)
extended_arg = 0
while i < L:
op = code[i]
i+= 1
if op < opcode.HAVE_ARGUMENT:
yield [op, None]
continue
oparg = code[i] + (code[i+1] << 8) + extended_arg
extended_arg = 0
i += 2
if op == opcode.EXTENDED_ARG:
extended_arg = oparg << 16
continue
yield [op, oparg]
def write_instruction(inst):
op, oparg = inst
if oparg is None:
return [chr(op)]
elif oparg <= 65536L:
return [chr(op), chr(oparg & 255), chr((oparg >> 8) & 255)]
elif oparg <= 4294967296L:
return [chr(opcode.EXTENDED_ARG),
chr((oparg >> 16) & 255),
chr((oparg >> 24) & 255),
chr(op),
chr(oparg & 255),
chr((oparg >> 8) & 255)]
else:
raise ValueError("Invalid oparg: {0} is too large".format(oparg))
if __name__=='__main__':
import dis
class Foo(object):
y = 1
z = 1
def test(x):
foo = Foo()
foo.y = 1
foo = x + y + z + foo.y
print foo
code_obj = append_arguments(test.func_code, ('y',))
f = types.FunctionType(code_obj, test.func_globals, argdefs=(1,))
if DEBUGGING:
dis.dis(test)
print '-'*20
dis.dis(f)
f(1)
Note that a whole branch of this code (that relating to EXTENDED_ARG) is untested but that for common cases, it seems to be pretty solid. I'll be hacking on it and am currently writing some code to validate the output. Then (when I get around to it) I'll run it against the whole standard library and fix any bugs.
I'll also probably be implementing the first option as well.
A:
Edited answer -- restores namespace dict after calling user_func()
Tested using Python 2.7.5 and 3.3.2
File framework.py:
# framework objects
class Cat: pass
class Mouse: pass
class Cheese: pass
_namespace = {'Cat':Cat, 'Mouse':Mouse, 'Cheese':Cheese } # names to be injected
# framework decorator
from functools import wraps
def wrap(f):
func_globals = f.func_globals if hasattr(f,'func_globals') else f.__globals__
@wraps(f)
def wrapped(*args, **kwargs):
# determine which names in framework's _namespace collide and don't
preexistent = set(name for name in _namespace if name in func_globals)
nonexistent = set(name for name in _namespace if name not in preexistent)
# save any preexistent name's values
f.globals_save = {name: func_globals[name] for name in preexistent}
# temporarily inject framework's _namespace
func_globals.update(_namespace)
retval = f(*args, **kwargs) # call function and save return value
# clean up function's namespace
for name in nonexistent:
del func_globals[name] # remove those that didn't exist
# restore the values of any names that collided
func_globals.update(f.globals_save)
return retval
return wrapped
Example usage:
from __future__ import print_function
import framework
class Cat: pass # name that collides with framework object
@framework.wrap
def user_func():
print('in user_func():')
print(' Cat:', Cat)
print(' Mouse:', Mouse)
print(' Cheese:', Cheese)
user_func()
print()
print('after user_func():')
for name in framework._namespace:
if name in globals():
print(' {} restored to {}'.format(name, globals()[name]))
else:
print(' {} not restored, does not exist'.format(name))
Output:
in user_func():
Cat: <class 'framework.Cat'>
Mouse: <class 'framework.Mouse'>
Cheese: <class 'framework.Cheese'>
after user_func():
Cheese not restored, does not exist
Mouse not restored, does not exist
Cat restored to <class '__main__.Cat'>
A:
Sounds like you maybe want to be using exec code in dict, where code is the user's function and dict is a dictionary you provide which can
be pre-filled with references to objects that the user code should be able to use
store any functions or variables declared by the user's code for later use by your framework.
Docs for exec: http://docs.python.org/reference/simple_stmts.html#the-exec-statement
However, I'm pretty sure that this would only work if the user's code is being brought in as a string and you need to exec it. If the function is already compiled, it will already have its global bindings set. So doing something like exec "user_func(*args)" in framework_dict won't work, because user_func's globals are already set to the module in which it was defined.
Since func_globals is readonly, I think you'll have to do something like what martineau suggests in order to modify the function globals.
I think it likely (unless you're doing something unprecedentedly awesome, or I'm missing some critical subtlety) that you probably would be better off putting your framework objects into a module, and then have the user code import that module. Module variables can be reassigned to or mutated or accessed quite readily by code that's been defined outside of that module, once the module has been imported.
I think this would be better for code readibility also, because user_func will end up having explicit namespacing for Cat, Dog, etc. rather than readers unfamiliar with your framework having to wonder where they came from. E.G. animal_farm.Mouse.eat(animal_farm.Cheese), or maybe lines like
from animal_farm import Goat
cheese = make_cheese(Goat().milk())
If you are doing something unprecedently awesome, I think you'll need to use the C API to pass arguments to a code object. It looks like the function PyEval_EvalCodeEx is the one you want.
A:
If your application is strictly Python 3, I don't see how using Python 3's nonlocal is any uglier than writing a decorator to manipulate function's local namespace. I say give the nonlocal solution a try or rethink this strategy.
| Function local name binding from an outer scope | I need a way to "inject" names into a function from an outer code block, so they are accessible locally and they don't need to be specifically handled by the function's code (defined as function parameters, loaded from *args etc.)
The simplified scenario: providing a framework within which the users are able to define (with as little syntax as possible) custom functions to manipulate other objects of the framework (which are not necessarily global).
Ideally, the user defines
def user_func():
Mouse.eat(Cheese)
if Cat.find(Mouse):
Cat.happy += 1
Here Cat, Mouse and Cheese are framework objects that, for good reasons, cannot be bounded to the global namespace.
I want to write a wrapper for this function to behave like this:
def framework_wrap(user_func):
# this is a framework internal and has name bindings to Cat, Mouse and Cheese
def f():
inject(user_func, {'Cat': Cat, 'Mouse': Mouse, 'Cheese': Cheese})
user_func()
return f
Then this wrapper could be applied to all user-defined functions (as a decorator, by the user himself or automatically, although I plan to use a metaclass).
@framework_wrap
def user_func():
I am aware of the Python 3's nonlocal keyword, but I still consider ugly (from the framework's user perspective) to add an additional line:
nonlocal Cat, Mouse, Cheese
and to worry about adding every object he needs to this line.
Any suggestion is greatly appreciated.
| [
"The more I mess around with the stack, the more I wish I hadn't. Don't hack globals to do what you want. Hack bytecode instead. There's two ways that I can think of to do this. \n1) Add cells wrapping the references that you want into f.func_closure. You have to reassemble the bytecode of the function to use LOAD... | [
11,
4,
3,
1
] | [] | [] | [
"decorator",
"python",
"scope"
] | stackoverflow_0003908335_decorator_python_scope.txt |
Q:
WSGI request and response wrappers for Python 3
Are there WSGI request and response wrappers for Python 3?
WebOb looks nice (although there is some critique), but it seems to be written in Python <3. Werkzeug seems also to be written in Python <3.
Should I write my own request and response wrappers for Python 3? Maybe this would be impossible, since WSGI seems to be somewhat broken in Python 3. So what to do? Give up Python 3 and go back to Python 2?
A:
My recommendation: right now, Python 2.x should be used for production quality stuff. I know, Python 3 is technically very interesting, but right now sticking with Python 2 is MUCH easier and MUCH more productive.
A:
No, there are not WSGI for Python3. It occurs because of new string types.
| WSGI request and response wrappers for Python 3 | Are there WSGI request and response wrappers for Python 3?
WebOb looks nice (although there is some critique), but it seems to be written in Python <3. Werkzeug seems also to be written in Python <3.
Should I write my own request and response wrappers for Python 3? Maybe this would be impossible, since WSGI seems to be somewhat broken in Python 3. So what to do? Give up Python 3 and go back to Python 2?
| [
"My recommendation: right now, Python 2.x should be used for production quality stuff. I know, Python 3 is technically very interesting, but right now sticking with Python 2 is MUCH easier and MUCH more productive.\n",
"No, there are not WSGI for Python3. It occurs because of new string types.\n"
] | [
2,
0
] | [] | [] | [
"python",
"python_3.x",
"request",
"response",
"wsgi"
] | stackoverflow_0003725903_python_python_3.x_request_response_wsgi.txt |
Q:
How to load .bmp file into BitmapImage class Tkinter python
I'm unable to find any way to load .bmp file into Tkinter() so that I can use it in a canvas widget!Plz help me!
from Tkinter import *
from PIL import Image
import ImageTk
import tkFileDialog
import tkMessageBox
root=Tk()
class lapp:
def __init__(self,master):
w=Canvas(root,width=300,height=300)
w.pack()
p=Image.open("001.bmp")
tkimage=ImageTk.PhotoImage(p)
w.creat_image(0,0,image=tkimage)
App=lapp(root)
root.mainloop()
Its not showing any image on the canvas, its just blank!
Btw I'm using win7 with python 2.7
A:
This works for me.
The image doesn't show when I use the Tk PhotoImage class. But it works ok when using PIL.
My image size is 50*250, so I've put coordinates that center it (25, 125)
from Tkinter import *
from PIL import Image, ImageTk
root=Tk()
root.title("My Image")
w = Canvas(root, width=50, height=250)
image = Image.open("blog0.bmp")
w.create_image((25, 125), image=ImageTk.PhotoImage(image))
w.pack()
root.mainloop()
I hope it helps
| How to load .bmp file into BitmapImage class Tkinter python | I'm unable to find any way to load .bmp file into Tkinter() so that I can use it in a canvas widget!Plz help me!
from Tkinter import *
from PIL import Image
import ImageTk
import tkFileDialog
import tkMessageBox
root=Tk()
class lapp:
def __init__(self,master):
w=Canvas(root,width=300,height=300)
w.pack()
p=Image.open("001.bmp")
tkimage=ImageTk.PhotoImage(p)
w.creat_image(0,0,image=tkimage)
App=lapp(root)
root.mainloop()
Its not showing any image on the canvas, its just blank!
Btw I'm using win7 with python 2.7
| [
"This works for me. \nThe image doesn't show when I use the Tk PhotoImage class. But it works ok when using PIL.\nMy image size is 50*250, so I've put coordinates that center it (25, 125)\nfrom Tkinter import *\nfrom PIL import Image, ImageTk\n\nroot=Tk()\n\nroot.title(\"My Image\")\n\nw = Canvas(root, width=50, he... | [
1
] | [] | [] | [
"bitmap",
"bmp",
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0003913037_bitmap_bmp_python_python_imaging_library_tkinter.txt |
Q:
Python: read user-input directly from the prompt
I have to validate user-input from stdin that is not going to be entered by hitting the Enter-key.
So readline() and other Enter-dependent functions are of no use to me.
Practically the promt will be filled, and each keystroke has to be handled as an event. How do I get access to the promt buffer's contents?
A:
See if it helps
http://code.activestate.com/recipes/134892/
A:
I'm unclear what you mean by "prompt", but it sounds like you need to respond to individual key-presses, rather than textual input.
This is covered in the Python FAQ under "How do I get a single keypress at a time?"
| Python: read user-input directly from the prompt | I have to validate user-input from stdin that is not going to be entered by hitting the Enter-key.
So readline() and other Enter-dependent functions are of no use to me.
Practically the promt will be filled, and each keystroke has to be handled as an event. How do I get access to the promt buffer's contents?
| [
"See if it helps\nhttp://code.activestate.com/recipes/134892/\n",
"I'm unclear what you mean by \"prompt\", but it sounds like you need to respond to individual key-presses, rather than textual input.\nThis is covered in the Python FAQ under \"How do I get a single keypress at a time?\"\n"
] | [
2,
2
] | [] | [] | [
"events",
"interactive",
"prompt",
"python"
] | stackoverflow_0003913663_events_interactive_prompt_python.txt |
Q:
Can anyone explain the difference between XMLRPC, SOAP and also the C# Web Service?
Are they just the same protocol or something different?
I am just confused about it.
Actually, I want to call a web service written in C# with ASP.NET by Python. I have tried XMLRPC but it seems just did not work.
So what is the actually difference among them?
Thanks.
A:
All of them use the same transport protocol (HTTP).
XMLRPC formats a traditional RPC call with XML for remote execution.
SOAP wraps the call in a SOAP envelope (still XML, different formatting, oriented towards message based services rather than RPC style calls).
If you're using C#, your best bet is probably SOAP based Web Services (at least out of the options you listed).
A:
In order to call web service written in C#, you will need SOAP library that is able to consume WSDL (check it out in addition to all the useful terms mentioned here). Couple of the libraries i came across:
suds is a lightweight SOAP python client.
ZSI is more powerful library that also has WSDL consumption of complex types.
SOAPpy was good library. Unfortunately it was not updated since 2005-02-22, so i provided it here only for reference.
Python Web services page has more information and links on different related libraries.
A:
They are completely different protocols, you need to find out the protocol used by the web service you wish to consume and program to that. Web services is really just a concept XML-RPC, SOAP and REST are actual technologies the implement this concept. These implementations are not interoperable (without some translation layer).
All these protocols enable basically the same sort of thing, calling into remote some application over the web. However the details of how they do this differ, they are not just different names for the same protocol.
A:
xml-rpc: Its a mechanism to call remote procedure & function accross network for distributed system integration. It uses XML based message document and HTTP as transport protocol. Further, it only support 6 basic data type as well as array for communication.
SOAP: SOAP is also XML-based protocol for information exchange using HTPP transport protocol. However, it is more advanced then XML-RPC protocol. It uses XML formatted message that helps communicating complex data types accross distributed application, and hence is widely used now a days.
| Can anyone explain the difference between XMLRPC, SOAP and also the C# Web Service? | Are they just the same protocol or something different?
I am just confused about it.
Actually, I want to call a web service written in C# with ASP.NET by Python. I have tried XMLRPC but it seems just did not work.
So what is the actually difference among them?
Thanks.
| [
"All of them use the same transport protocol (HTTP).\nXMLRPC formats a traditional RPC call with XML for remote execution.\nSOAP wraps the call in a SOAP envelope (still XML, different formatting, oriented towards message based services rather than RPC style calls).\nIf you're using C#, your best bet is probably SO... | [
5,
4,
3,
1
] | [] | [] | [
"c#",
"python",
"web_services",
"xml_rpc"
] | stackoverflow_0001847534_c#_python_web_services_xml_rpc.txt |
Q:
How does this Python Lambda recursion expression work?
rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
I am new to Python and trying to understand how lambda expressions work. Can somebody explain how this recursion is working? I am able to understand that 10==11 will be 'false' and that's how rec_fn will be called again and again recursively.
But what I am not able to get is this seemingly new way of writing a lambda expression.
whatever happened to lambda x: x+y where there is a parameter 'x' going into the unnamed function?
Also, why is
rec_fn() = lambda: .... // a syntax error
rec_fn = lambda: .... //syntactically correct - WHY?
What is rec_fn? Is it a function or a variable?
A:
It may help to think of a function call as an operator. Because that's what it is. When you do rec_fn() you are doing two things. First, you're getting a reference to the object named rec_fn. This happens to be a function, but that doesn't matter (in Python, objects besides functions are callable). Then there is () which means "call the object I just named." It is possible to get a reference to a function without calling it, just by leaving off the parentheses, and then you can assign it different names, any of which can then be used to call it by adding the parentheses.
def func1():
print "func1"
func2 = func1
func2() # prints "func1"
Now you can see how the lambda works.
func3 = lambda x: x+1
You are doing the same as the func2 = func1 line above, except the lambda expression is the function. The syntax is just different; the lambda function can be defined without giving it a name.
Lambdas can have any number of parameters, so lambda: 3 is a function that takes no parameters and always returns 3, while lambda x, y: x+y is a function that takes two parameters and returns their sum.
As to the way or is being used, it's taking advantage of short-circuiting. Basically, or knows that if its first operand is True, it doesn't need to evaluate the second, because the result is going to be True regardless of what the second argument is. You could thus read this as if not 10==11: rec_fn(). By the way, and also short-circuits, although it does so if the first argument is False since it knows that the result will be False regardless of what the second argument is.
A:
A function invocation -- x() -- is an expression. It is lot a legal syntax construct on the left side of an assignment. What should happen? (It is roughly the same as saying 42 = lambda: ....)
In the 2nd case, you are simply assigning the new function object created (with the lambda keyword) to a variable (named rec_fn) and not invoking a function.
Perhaps a more clear way is to use the (preferred) non-lambda nested function approach:
# just for example, not really useful as it is unless you like to eat CPU
def rec_fn():
return 10 == 11 or rec_fn()
rec_fn()
The lambda keyword is just a syntactic shortcut which can be used as part of an expression.
rec_fn is a local variable in the above cases (assuming said code is nested in a function/method). The rec_fn variable stores a function object which can later be invoked with (). Methods are roughly the same (functions which can be invoked), but they are properties and not variables.
A:
rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
is the similar to this expression, however this one requires a parameter,
rec_fn = lambda x: 10==11 or rec_fn(x)
x = ...
rec_fn(x)
whereas you'r rec_fn() with you're calling a function with no parameters hence no x
rec_fn() = lambda: .... // a syntax error
This is trying to set result of the function call rec_fn() (a right had side expression) to a value. There is no variabele there to assign the lambda function to.
rec_fn = lambda: .... //syntactically correct - WHY?
here rec_fn in the variable that holds the lambda (in essence like a function pointer)
A:
rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
The body of a function is not evaluated until it is executed. At the start, rec_fn has no value. The contents of the lambda is just some expression that has some function call on some variable rec_fn. It won't fail yet because the function isn't executed yet. The new lambda function is then assigned to the variable rec_fn followed by a call to the function. Now since the function is being executed, it will go through the motions up to the function call. The expression is 10==11 or rec_fn(). It's an or expresison so the left hand side is evaluated. 10==11 is False so it must evaluate the right hand side which is a function call to some function (or other callable object) rec_fn. At that point, rec_fn is assigned to the function we just created (itself) so it gets called (recursively). And so on. It is equivalent to:
def rec_fn():
return 10==11 or rec_fn()
Lambdas can be written using as many parameters as necessary. In the case of lambda: ..., there are none specified so it's a "function that takes no arguments."
Just remember, functions (and by extension, lambdas) are first class objects. You can pass them around like any other object and store them into other variables.
rec_fn = lambda: ...
is fine because you've defined a lambda function and stored it into the variable rec_fn. It can be called by using that name rec_fn() like you would any other function.
rec_fn() = lambda: ...
on the other hand fails because you cannot assign anything to the result of the function call rec_fn().
Defining a function this way is much different than a normal function definition:
def rec_fn2(): # here you may use the parens with the name to indicate it takes no arguments
... # unlike in the lambda assignment above
Just try to remember the difference.
A:
This is maybe more understandable example of recursion, factorial lambda version:
fact = lambda x: 1 if x == 0 else x*fact(x-1)
prin(fact(10))
Output:
3628800
Be aware of Python's recursion limit, though.
Example of using or as this if..else:
print 1 or 'a'
print 'a' or False
print False or True or 0/9
fact_or = lambda x: x == 0 and 1 or x * fact_or(x-1)
print fact_or(10)
| How does this Python Lambda recursion expression work? | rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
I am new to Python and trying to understand how lambda expressions work. Can somebody explain how this recursion is working? I am able to understand that 10==11 will be 'false' and that's how rec_fn will be called again and again recursively.
But what I am not able to get is this seemingly new way of writing a lambda expression.
whatever happened to lambda x: x+y where there is a parameter 'x' going into the unnamed function?
Also, why is
rec_fn() = lambda: .... // a syntax error
rec_fn = lambda: .... //syntactically correct - WHY?
What is rec_fn? Is it a function or a variable?
| [
"It may help to think of a function call as an operator. Because that's what it is. When you do rec_fn() you are doing two things. First, you're getting a reference to the object named rec_fn. This happens to be a function, but that doesn't matter (in Python, objects besides functions are callable). Then there is (... | [
4,
0,
0,
0,
0
] | [] | [] | [
"lambda",
"python",
"recursion"
] | stackoverflow_0003911705_lambda_python_recursion.txt |
Q:
Django - ManyToManyField in a model, setting it to null?
I have a django model (A) which has a ManyToManyField (types) to another model (B). Conceptually the field in A is an 'optionally limit this object to these values'. I have set blank=null and null=True on the ManyToManyField. I have created an object from this model, and set types to some values. All is good.
I want to set it to 'null', i.e. disable it. But in the django shell, I get the following errors:
>>> o.types.all()
[<Type: foo>, <Type: bar>]
>>> o.types = None
File "<console>", line 1, in <module>
File ".../virtualenv/lib/python2.6/site-packages/django/db/models/fields/related.py", line 627, in __set__
manager.add(*value)
TypeError: add() argument after * must be a sequence, not NoneType
I can successfully set it to [] (the empty list), but I would like to set it to None, since I want to use None as a signal/flag. Is this possible in Django models?
I'm using Django 1.1
A:
That's what clear() is for.
http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear
Perhaps you're looking for remove()?
http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove
A:
I don't think it is possible to set it to None - think about how M2M is implemented on the SQL layer (it is an intermidiate table, where can you write your "None" to?).
If you need a separate flag, why not introduce another column?
| Django - ManyToManyField in a model, setting it to null? | I have a django model (A) which has a ManyToManyField (types) to another model (B). Conceptually the field in A is an 'optionally limit this object to these values'. I have set blank=null and null=True on the ManyToManyField. I have created an object from this model, and set types to some values. All is good.
I want to set it to 'null', i.e. disable it. But in the django shell, I get the following errors:
>>> o.types.all()
[<Type: foo>, <Type: bar>]
>>> o.types = None
File "<console>", line 1, in <module>
File ".../virtualenv/lib/python2.6/site-packages/django/db/models/fields/related.py", line 627, in __set__
manager.add(*value)
TypeError: add() argument after * must be a sequence, not NoneType
I can successfully set it to [] (the empty list), but I would like to set it to None, since I want to use None as a signal/flag. Is this possible in Django models?
I'm using Django 1.1
| [
"That's what clear() is for.\nhttp://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear\nPerhaps you're looking for remove()?\nhttp://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove\n",
"I don't think i... | [
14,
1
] | [] | [] | [
"django",
"django_models",
"manytomanyfield",
"python"
] | stackoverflow_0003913499_django_django_models_manytomanyfield_python.txt |
Q:
about textarea \r\n or \n in python
i have tested code in firefox under ubuntu:
the frontend is a textarea,in textarea press the key ENTER,then submit to the server,
on the backend you'll get find \r\n string
r=request.POST.get("t")
r.find("\r\n")>-1:
print "has \r\n"
my question is when we will get \r\n ,when we'll get \n?is this platform independent?
this is important when want to use this string to use as a regular expression,any adivse is welcome
A:
Yes, you are correct, you are dealing with a platform-specific ways to encode a newline:
In Windows platforms, a newline is typically encoded as \r\n
In Linux/Unix/OS X, a newline is typically encoded as \n
Similarly, web browsers tend to favor these conventions: IE uses \r\n newlining, whereas Safari and Firefox use \n.
As a solution, considering using Python functions that are aware of different new line encodings, e.g. provide a universal newline support.
For instance if you want to split a string into lines, use splitlines:
lines = r.splitlines()
| about textarea \r\n or \n in python | i have tested code in firefox under ubuntu:
the frontend is a textarea,in textarea press the key ENTER,then submit to the server,
on the backend you'll get find \r\n string
r=request.POST.get("t")
r.find("\r\n")>-1:
print "has \r\n"
my question is when we will get \r\n ,when we'll get \n?is this platform independent?
this is important when want to use this string to use as a regular expression,any adivse is welcome
| [
"Yes, you are correct, you are dealing with a platform-specific ways to encode a newline:\n\nIn Windows platforms, a newline is typically encoded as \\r\\n\nIn Linux/Unix/OS X, a newline is typically encoded as \\n\n\nSimilarly, web browsers tend to favor these conventions: IE uses \\r\\n newlining, whereas Safari ... | [
5
] | [] | [] | [
"python",
"textarea"
] | stackoverflow_0003913830_python_textarea.txt |
Q:
"Pythonic" multithreaded (Concurrent) language
I now primarily write in python, however I am looking for a language that is more thread friendly (not JAVA,C#,C or C++).
Python's threads are good when they are IO bound but it's coming up short when I am doing something CPU intensive.
Any ideas?
Thanks,
James
A:
Clojure is pretty fun, if you're into that sort of thing. It's a lisp that runs on the JVM. Apparently it's as fast as Java for a lot of things, despite being dynamically typed *. Java interop is about as convenient as I could imagine possible, though the native clojure libraries are already decent enough that you don't need to hit up Java for most things.
It also adds some "scripting language" sensibilities, like maps (-> Python dicts) and vectors (-> Python lists) to help reduce the likelihood of parenthetical paroxysm.
Oh right, concurrency. It uses a software transactional memory system which is pretty interesting in and of itself. Extra, extra: Read all about it.
*: I think you may need to use "type hinting" to get Java-like speed for a lot of tasks. This is made quite convenient in Clojure.
A:
Before anything else, what programming problem are you trying to solve? Has the GIL actually become a bottleneck yet? (If you're not sure, it probably hasn't.)
Without knowing this, you risk looking for a nail that fits your hammer, instead of the other way around.
If you really, really know that the GIL has become a bottleneck, and that you need to crunch numbers across multiple processors, then you want to consider:
If you have known CPU-critical sections, compile them with C type declarations using Pyrex/Cython, if you can. This will firstly make them much more CPU-efficient than Python bytecode interpretation, and as a bonus, allow you to release the GIL around sections that don't need it. (Moral: turn your donkeys into racehorses before trying to parallelize them.)
It should go without saying, but if you're using any CPU-intensive extension modules, make sure they're not already releasing the GIL for you.
For almost everything else, use the built-in multiprocessing module. This gives you roughly the same API and advantages as threading, but provides you with true process-level concurrency: among other things, this allows you to easily run your CPU-intensive code on multiple machines in concert, which is critical if your problem actually gets big.
A:
boo's syntax is Python-inspired. The programming language is a bit different, though: It's strongly typed with type-inference, and it's most imporant feature is probably the open compiler pipeline, i.e. the ability to create syntactic macros (in the LISP sense of the word "macro", not in the C sense of "preprocessor macro").
And, obviously, IronPyton is quite pythonic and about as good at threading as other .NET languages.
A:
Stackless Python as used by the EVE online developers might fit.
Stackless Python is an enhanced
version of the Python programming
language. It allows programmers to
reap the benefits of thread-based
programming without the performance
and complexity problems associated
with conventional threads. The
microthreads that Stackless adds to
Python are a cheap and lightweight
convenience, which if used properly,
can not only serve as a way to
structure an application or framework,
but by doing so improve program
structure and facilitate more readable
code.
A:
to overcome GIL, you can try interpreting python language with jython instead of cpython
A:
Python falls short when it comes to CPU intensive tasks because Python isn't a very efficient language. Many "dynamic" languages have that problem, since the compiler is limited in what it can assume about the program at compile-time. Method-calls, for example, may have to be looked up every single time in case someone has replaced the method on the object between each invokation.
I would recommend that you take a look at Erlang, even though it probably isn't "Pythonic" in your sense of the word. :-)
A:
Take the hint. CPU intensive programs can also be made into multiple processes. Multiple processes and a pipeline to pass status around can often have outstanding performance.
Rather than fish around randomly for other languages, do this.
Decompose the problem into a pipeline of steps that can be done concurrently.
In the shell, the top-level script is this: a.py | b.py | c.py | d.py...
Write each step as a very small Python loop that reads from sys.stdin and writes to sys.stdout. Interesting, this is the default for raw_input() and print() making things simple.
Measure the performance.
You'll -- correctly -- spend all your time designing your algorithm. You'll spend little time coding or learning a new language. You'll trivially tie up every core on every CPU available to you. You'll spend no time on thread synchronization or other foolishness.
This kind of thing works very, very well for "CPU Intensive" applications.
A:
You could just use python multiprocessing it mirrors the API of threading but runs separate processes. Might not be implemented for non-posix. For general CPU intensive problems you could always try Stackless Python (mentioned already) or Pyrex.
| "Pythonic" multithreaded (Concurrent) language | I now primarily write in python, however I am looking for a language that is more thread friendly (not JAVA,C#,C or C++).
Python's threads are good when they are IO bound but it's coming up short when I am doing something CPU intensive.
Any ideas?
Thanks,
James
| [
"Clojure is pretty fun, if you're into that sort of thing. It's a lisp that runs on the JVM. Apparently it's as fast as Java for a lot of things, despite being dynamically typed *. Java interop is about as convenient as I could imagine possible, though the native clojure libraries are already decent enough that ... | [
7,
4,
3,
2,
1,
1,
1,
1
] | [] | [] | [
"concurrency",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0003911897_concurrency_multiprocessing_multithreading_python.txt |
Q:
Question about python string
i have been asked to write a function which should be called in this way
foo("Hello")
This function also has to return values in this way:
[Hello( user = 'me', answer = 'no', condition = 'good'),
Hello( user = 'you', answer = 'yes', condition = 'bad'),
]
the task has clearly asked to return string values. can anyone understand the purpose of this task in concepts of Python and help me on this?
would you please give me a code sample?
A:
Functions
Lists
Classes
Create a class that has the desired attributes, then return a list of instances from the function.
A:
It could be something like this:
class Hello:
def __init__(self, user, answer, condition):
self.user = user
self.answer = answer
self.condition = condition
def foo():
return [Hello( user = 'me', answer = 'no', condition = 'good'),
Hello( user = 'you', answer = 'yes', condition = 'bad'),
]
Output of the foo function:
[<__main__.Hello instance at 0x7f13abd761b8>, <__main__.Hello instance at 0x7f13abd76200>]
Which is a list of class instances (objects).
You can use them this way:
for instance in foo():
print instance.user
print instance.answer
print instance.condition
Which gives:
me
no
good
you
yes
bad
| Question about python string | i have been asked to write a function which should be called in this way
foo("Hello")
This function also has to return values in this way:
[Hello( user = 'me', answer = 'no', condition = 'good'),
Hello( user = 'you', answer = 'yes', condition = 'bad'),
]
the task has clearly asked to return string values. can anyone understand the purpose of this task in concepts of Python and help me on this?
would you please give me a code sample?
| [
"Functions\nLists\nClasses\nCreate a class that has the desired attributes, then return a list of instances from the function.\n",
"It could be something like this:\nclass Hello:\n def __init__(self, user, answer, condition):\n self.user = user\n self.answer = answer\n self.condition = con... | [
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003912617_python_string.txt |
Q:
Query refresh issue after using MySQL to load file
I use SqlAlchemy as my ORM. I do a mysqlimport cmd through subprocess. Then before and after the execution, I query the db records with the statistics_db method.
But the records count results after import from CSV didn't increase. I think this is an SqlAlchemy problem.
def statistics_db(f):
@wraps(f)
def wrapper(*args,**args2):
q=Product.query.filter("site='%s'"%g_site_show_name)
pre=q.count()
print "当前数据库中共有%s条关于%s的记录"%(q.count(),g_site_show_name)
time.sleep(3)
back = f(*args, **args2)
post=q.count()
count=pre-post
description="减少" if count>0 else "增加"
print "当前数据库中共有%s条关于%s的记录"%(q.count(),g_site_show_name)
print "%s了%s条记录"%(description,abs(count))
return back
return wrapper
@cost_time
@statistics_db
def batch_csv2db():
"将csv文件中的数据批量导入到数据库中"
if not os.path.exists(g_xml2csv_file):
print "找到压缩文件,从中读取csv文件"
dirname,filename=os.path.split(src)
base,ext=os.path.splitext(filename)
tar_filepath=os.path.join(dirname,base+".tar.gz")
uncompress(tar_filepath)
if not os.path.exists(g_xml2csv_file):
print "未找到可用的csv文件!"
return
cmd="""mysqlimport -u root --password='bin' -L -v --columns='name,price,productid,site,link,smallImage,bigImage,description,createdOn,modifiedOn,size,weight,wrap,material,packagingCount,stock,location,popularity,inStock,categories' --fields-terminated-by=',' --fields-enclosed-by='"' --fields-escaped-by='\\' --lines-terminated-by='\n' search """+g_xml2csv_file
args=shlex.split(cmd)
p=subprocess.Popen(args)
stdout, stderr = p.communicate()
print stdout,stderr
A:
You have to either call commit()/rollback() to end transaction after calling count() or change isolation level. Otherwise you won't see changes made from other connections.
| Query refresh issue after using MySQL to load file | I use SqlAlchemy as my ORM. I do a mysqlimport cmd through subprocess. Then before and after the execution, I query the db records with the statistics_db method.
But the records count results after import from CSV didn't increase. I think this is an SqlAlchemy problem.
def statistics_db(f):
@wraps(f)
def wrapper(*args,**args2):
q=Product.query.filter("site='%s'"%g_site_show_name)
pre=q.count()
print "当前数据库中共有%s条关于%s的记录"%(q.count(),g_site_show_name)
time.sleep(3)
back = f(*args, **args2)
post=q.count()
count=pre-post
description="减少" if count>0 else "增加"
print "当前数据库中共有%s条关于%s的记录"%(q.count(),g_site_show_name)
print "%s了%s条记录"%(description,abs(count))
return back
return wrapper
@cost_time
@statistics_db
def batch_csv2db():
"将csv文件中的数据批量导入到数据库中"
if not os.path.exists(g_xml2csv_file):
print "找到压缩文件,从中读取csv文件"
dirname,filename=os.path.split(src)
base,ext=os.path.splitext(filename)
tar_filepath=os.path.join(dirname,base+".tar.gz")
uncompress(tar_filepath)
if not os.path.exists(g_xml2csv_file):
print "未找到可用的csv文件!"
return
cmd="""mysqlimport -u root --password='bin' -L -v --columns='name,price,productid,site,link,smallImage,bigImage,description,createdOn,modifiedOn,size,weight,wrap,material,packagingCount,stock,location,popularity,inStock,categories' --fields-terminated-by=',' --fields-enclosed-by='"' --fields-escaped-by='\\' --lines-terminated-by='\n' search """+g_xml2csv_file
args=shlex.split(cmd)
p=subprocess.Popen(args)
stdout, stderr = p.communicate()
print stdout,stderr
| [
"You have to either call commit()/rollback() to end transaction after calling count() or change isolation level. Otherwise you won't see changes made from other connections.\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003906262_python_sqlalchemy.txt |
Q:
Simple graphics API with transparency, polygons, reading image pixels?
I need a simple graphics library that supports the following functionality:
Ability to draw polygons (not just rectangles!) with RGBA colors (i.e., partially transparent),
Ability to load bitmap images,
Ability to read current color of pixel in a given coordinate.
Ideally using JavaScript or Python.
Seems like HTML 5 Canvas can handle #2 and #3 but not #1, whereas SVG can handle #1 and #2 but not #3. Am I missing something (about either of these two)? Or are there other alternatives?
A:
PyGame can do all of those things. OTOH, I don't think it embeds into a GUI too well.
A:
I ended up going with Canvas. The "secret" of polygons is using paths. Thanks, "tur1ng"!
A:
GameJs does that and more - it's similar to the mentioned PyGame.
http://gamejs.org
Ability to draw polygons (not just rectangles!) with RGBA colors (i.e., partially transparent),
gamejs.draw.polygon (surface, color, pointlist, width)
Transparent colors can be defined as 'rgba(50, 50, 50, 0.1)' (last is alpha)
http://docs.gamejs.org/gamejs/draw/#polygon
Ability to load bitmap images,
var surface = gamejs.image.load('images/foo.png')
http://docs.gamejs.org/gamejs/image/
Ability to read current color of pixel in a given coordinate.
// a surface array is a special DOM canvas array
// that is superfast for per pixel access / manipulation
var srfArray = new SurfaceArray(display);
srfArray.set(50, 100, [255, 0, 0, 100]);
srfArray.get(20, 30);
http://docs.gamejs.org/gamejs/surfacearray/
A:
I voted for PyGame, but I would also like to point out that the new QT graphics library seems quite capable. I have not used PyQT with QT4 yet, but I really like PyQT development with QT3.
| Simple graphics API with transparency, polygons, reading image pixels? | I need a simple graphics library that supports the following functionality:
Ability to draw polygons (not just rectangles!) with RGBA colors (i.e., partially transparent),
Ability to load bitmap images,
Ability to read current color of pixel in a given coordinate.
Ideally using JavaScript or Python.
Seems like HTML 5 Canvas can handle #2 and #3 but not #1, whereas SVG can handle #1 and #2 but not #3. Am I missing something (about either of these two)? Or are there other alternatives?
| [
"PyGame can do all of those things. OTOH, I don't think it embeds into a GUI too well.\n",
"I ended up going with Canvas. The \"secret\" of polygons is using paths. Thanks, \"tur1ng\"!\n",
"GameJs does that and more - it's similar to the mentioned PyGame.\nhttp://gamejs.org\nAbility to draw polygons (not just r... | [
3,
2,
1,
0
] | [
"maybe Raphael - http://raphaeljs.com/reference.html\n"
] | [
-1
] | [
"canvas",
"graphics",
"javascript",
"python",
"svg"
] | stackoverflow_0003021514_canvas_graphics_javascript_python_svg.txt |
Q:
Possible to do ordered dictionary in python 2.5 (due to GAE)?
I'm new to Python, and using Google App Engine, which is currently running only Python 2.5. Are there any built-in ways of doing an ordered dictionary, or do I have to implement something custom?
A:
Django provides a SortedDict class, which has the same functionality. If you are using django, you can just use from django.utils.datastructures import SortedDict.
Even if you're not using django, you can still take advantage of that implementation. Just get the datastructures.py file from the django source and save it somewhere importable.
http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py
A:
you can sort a dict.items() list (of tuples) .. can't?
A:
OrderedDict is new in 2.7, so no, there's no built-in way to do this - you'll have to implement your own.
Usually, an ordered dictionary is implemented as a dictionary of linked list nodes, linked in traversal order. This should be fairly straightforward to implement yourself.
| Possible to do ordered dictionary in python 2.5 (due to GAE)? | I'm new to Python, and using Google App Engine, which is currently running only Python 2.5. Are there any built-in ways of doing an ordered dictionary, or do I have to implement something custom?
| [
"Django provides a SortedDict class, which has the same functionality. If you are using django, you can just use from django.utils.datastructures import SortedDict.\nEven if you're not using django, you can still take advantage of that implementation. Just get the datastructures.py file from the django source and s... | [
4,
0,
0
] | [] | [] | [
"dictionary",
"google_app_engine",
"python",
"python_2.5"
] | stackoverflow_0003911494_dictionary_google_app_engine_python_python_2.5.txt |
Q:
Deploy a sub package with distutils and pip
I am wanting to create a suite of interrelated packages in Python. I would like them all to be under the same package but installable as separate components.
So, for example, installing the base package would provide the mypackage but there would be nothing in mypackage.subpackage until I install it separately.
Is this possible with distutils and pip?
A:
What you are looking for is called "namespace packages", see this SO question
| Deploy a sub package with distutils and pip | I am wanting to create a suite of interrelated packages in Python. I would like them all to be under the same package but installable as separate components.
So, for example, installing the base package would provide the mypackage but there would be nothing in mypackage.subpackage until I install it separately.
Is this possible with distutils and pip?
| [
"What you are looking for is called \"namespace packages\", see this SO question\n"
] | [
5
] | [] | [] | [
"distutils",
"pip",
"python"
] | stackoverflow_0003914253_distutils_pip_python.txt |
Q:
Python relative import causes syntaxerror: invalid syntax
I'm trying to install this great python module Python-Chrono to my python environment, but it fails at least with python 2.4.3 and 2.6.6 with the following error message:
Traceback (most recent call last):
File "setup.py", line 30, in ?
import chrono
File "/home/janne/python-chrono-0.3.0/chrono/__init__.py", line 22
from . import calendar
^
SyntaxError: invalid syntax
The setup is using relative import mechanism and it should work just fine, but in my environment it causes this error.
Is there a way to get this fixed? Have you seen this kind of behaviour in your projects?
A:
Python 2.4 doesn't support that syntax - it was introduced in Python 2.5.
(Are you 100% sure that it's failing with that message in 2.6?)
| Python relative import causes syntaxerror: invalid syntax | I'm trying to install this great python module Python-Chrono to my python environment, but it fails at least with python 2.4.3 and 2.6.6 with the following error message:
Traceback (most recent call last):
File "setup.py", line 30, in ?
import chrono
File "/home/janne/python-chrono-0.3.0/chrono/__init__.py", line 22
from . import calendar
^
SyntaxError: invalid syntax
The setup is using relative import mechanism and it should work just fine, but in my environment it causes this error.
Is there a way to get this fixed? Have you seen this kind of behaviour in your projects?
| [
"Python 2.4 doesn't support that syntax - it was introduced in Python 2.5.\n(Are you 100% sure that it's failing with that message in 2.6?)\n"
] | [
6
] | [] | [] | [
"python",
"python_import",
"relative_path"
] | stackoverflow_0003914245_python_python_import_relative_path.txt |
Q:
Python Servers fighting each others with sockets
I try to make two servers in a file, but they are fighting each other visibly
have anyone an idea to make them peace ?
here is my code :
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
from threading import Thread
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow :
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam
"""
def sendmail(exp,dest,msg):
server = dest.split("@")[1]
s = smtplib.SMTP("localhost")
s.sendmail(exp,dest,msg)
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Serversmtp(Thread):
def __init__self(self):
Thread.__init__(self)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 25)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
class Pages :
def root(self,cgi=None):
return """eNqtVV1zqkgQfedX3MrrbNVREBnu5ubWCCoajPiRaHyTxEGNiAKC8uu3B7Nb+7JvO1QNNAOnT5/u
6Xnc5vHhSXsMk8/bk5bv7tdjmNK7XRz9yNKPXw+f63z9cxevow12H8mf4TrbtFt/CCE6QnRFl2Z1
H4hOoh57EU2OmsRETQPx9/p/D+3fhhXMLRhVrw07yC/ANPSuaOi6BTavihB2UZiwrW1D2sNNp8KL
lwhUNheFLaRwoQVeJtDotUXAa0AUlYUmMwzw0YlV6KVeievixiUPM8zhndMrOexaBWhYyPn5hKqn
C3BLi0oPQWvgojJtAmSbyMXE+BLEIOMFD5N8j65/NFDeTAIMcunDtXxycKnsgBdnJsFxVMCWZhf2
83ZqYPz+Tgz7PVFwvlWAA+GgaloiQINhj5d2OELpNCxw5yotOFlgoYyZXXBxvqSYpW6oESKDokxr
b6vuAdVsSAyt/cRFUDsYdzqSMznx6CMDsN0TB29lIwJMXUkOmi1ykF58aM/n4wL2MeOKLYG2xvsl
KtZ3JTe/SNRgUJIE+pAYs61ykHRJAsc6FSTEpRaOwV6WrGClZmz2OGTYgKWVjftgqNrQ9Xgm+XlP
jMbDEWXtMiHG5q70yUFE9q0nAjaezXwc31otWEOmvRUQX30LVp4GKjuQsNW9DT+FfkmmBc8VYDB8
V4BzJcFXqSTgZOvPZNtbiiA5fB01tKdvXsA2s2iPuBtNAS8xFLnCgjmutmj210MCPNAP49UHJeWy
pJBbtW0OyNYDIbmtGGvjAZVBe7voSfYxv7o4xbYDq73bBncNmYqbH9cFuPykH15WVJfVZkWMjJiy
HgwnHQr5lQBb2r6mnNGLtickk8udRDNtZxSqktDktBOMlEVgxk4vFLaBONz1cLs5KuQ4CjA+EWq1
WWhK1AM9j09dAmSkie1sqZCtjRfW2Sigc0pSvigTEvaVRDeXE5JgxMz7Oguz1REDT3xqhPimRDwo
D6bK2nroSJ6v5inc2+W5ri2gTnTjHJMEB3KI55WYo3iLHPDdZCHvjKlo98AtOl3B+/0PH93Z+opr
N8oL3uuOKgjhb1GKTlMSGlU+UJECJh8D/eXEx63/ToDTtSgw1vYHeRe5Hvbk1TbQEW5DAZDyrggM
AvQqsoUpyc7T728L2jpMD505AVJE3I5JM3QWVNmNM3PxnTy1taZfYYSyK5ikbkJsxMQzUY4EV91l
Q8UpXFm3jeDePS6Dl4lGGiwJcPROaS/6A2Lvx8Z3WTQ/5zrKZGSCABTD0mM1Y+VAhiqCjGyn9d2+
SDPqX8wPq4DFyxtV8mvZhd3PtlRYSlQLxKhKUCrAzyVE5LdVyATofEugK9ui7lF32oja8f8x/mnb
d8Bfvx6e7kfHb+2U7o75j4c8yZMH9qDePmi/nzTtEfej5hH1yfMXx7rT9A=="""
def favico(self):
return """eNqdk39MVWUYx99zDrZkJJc/dGtqsVZKFmttFhcuF0wXC1bTZmq0qVuWa8t+/NXPW1MQCk3FMBKs
LNauoq6AAr2zsFLLHAN1YQXJryzJewXuhV29HO759JyX//uj9933vOe8e7/f5/k+73OUMmR6PEqe
meq5FKXmKKWyBLIlO9P7/zUiEzaB02GWt43ycHOUx2St6YwTtxP0DZ6n+LV5LH5DURgwWRJQ5L+p
eEi+Xa4zZbP+aD9pByLMaR5jdkuUuV9NcNuhKIFTI4DD0bON3P+Kha/coLDMouAtRYHwl72u6IvE
mNvwG57QddJCUdJbY6S3jGmN+w5fYTwhCnackor55FZK3AqTfFmXbDbxSx4T9g1ygh2or0cxTzuk
nrSZ2R5HHbpKSVMvjuPAlMOq3XexuErh26HwC3/ZlhmShwFJOPfPON6mTlKb+lGtf2J+McSixov8
Hom6VAaGf6Ww8hZyq8X7exb+KpOCCvGwRXHueJDkSFj77B6bpOnSMLVdfVwdv4477KlJXggWs2iH
gbdG4otG7nbx8K5oicbO4jv4eJ2XlrdX8131i4z0dIlSUqZDOBbm+YNFZAs3v1a4NdPw7xJsE2xV
NJQu5PNV8/ik5Gb2PpJBdLhfe74cGeTx+gVk75F4H5r4BF55970vddtl4JccvFKPg6tn89FyD8GX
ltLesFX7tSXvn3tOcPurJg/sU+TUCeol3z2GhteNv92g4B2D/esWcrH9CI7UMREbpe/Ep1wb6tEe
6o5VcG+ZxKy3yNtrkSMecgV5u6UPxMdS4V8b7NW1i0eHad2UxfEnFKG1s7jcFdL7+5rryHx5Pjkf
SMxaS/t/sGom2c/mkX7PNvf6NC40lhFaqTj7TArfPmlyprpU58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6"""
class Serverhttp(Thread):
def __init__(self):
Thread.__init__(self)
self.Pages = Pages()
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
self.balisep = re.compile("<\?.*\?>",re.DOTALL)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 41000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
def decompress_img(self,img):
img = zlib.decompress(base64.decodestring(img))
return img
def decompress_html(self,html) :
page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
page+=zlib.decompress(base64.decodestring(html))
commands = self.balisep.findall(page)
print commands
for c in commands :
command = c.replace("<? ","")
command = c.replace("<?","")
command = command.replace(" ?>","")
command = command.replace("?>","")
print command
with stdoutIO() as s:
exec(command)
page = page.replace(c,s.getvalue())
return page
def traitement(self,data):
url = self.POST.findall(data)
print url
print len(url)
url = self.GET.findall(data)
print url
url = url[0].replace("GET","")
url = url.replace("POST","")
url = url.replace("HTTP","")
url = url.replace(" ","")
print url
if url == "/favicon.ico":
return self.decompress_img(self.Pages.favico())
else :
return self.decompress_html(self.Pages.root())
if __name__ == "__main__":
swww = Serverhttp()
swww.start()
ssmtp = Serversmtp()
ssmtp.start()
sendmail("test@test.com","b@gmail.com","hello")
print "toto"
Regards and thanks all people
A:
it was better to use : SocketServer.BaseRequestHandler with handler
and one for each server :
as seen here :
# MetaProject v 0.21
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
import threading
import SocketServer
SocketServer.TCPServer.allow_reuse_address = True
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow (http://stackoverflow.com/):
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam,bstpierre
"""
def sendmail(exp,dest,msg):
server = dest.split("@")[1]
s = smtplib.SMTP("localhost")
s.sendmail(exp,dest,msg)
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Serversmtp(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024)
socket = self.request
print "%s wrote:" % self.client_address[0]
self.data = self.traitement(self.data)
socket.sendto(self.data, self.client_address)
def traitement(self,data):
return "toto"
class Pages :
def __init__(self):
self.balisep = re.compile("<\?.*\?>",re.DOTALL)
def root(self,cgi=None):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrJhECbpCKgWGZuukJxUbKtUlpiWWZyfp4ekFCyg8jZcxUUZeaVKCiV
5JfkK2krgUSVuOztuLhs9CFm2eiDjQYAG5wecg==""")
def faviconico(self):
return self.decompress_img("""eNqdk39MVWUYx99zDrZkJJc/dGtqsVZKFmttFhcuF0wXC1bTZmq0qVuWa8t+/NXPW1MQCk3FMBKs
LNauoq6AAr2zsFLLHAN1YQXJryzJewXuhV29HO759JyX//uj9933vOe8e7/f5/k+73OUMmR6PEqe
meq5FKXmKKWyBLIlO9P7/zUiEzaB02GWt43ycHOUx2St6YwTtxP0DZ6n+LV5LH5DURgwWRJQ5L+p
eEi+Xa4zZbP+aD9pByLMaR5jdkuUuV9NcNuhKIFTI4DD0bON3P+Kha/coLDMouAtRYHwl72u6IvE
mNvwG57QddJCUdJbY6S3jGmN+w5fYTwhCnackor55FZK3AqTfFmXbDbxSx4T9g1ygh2or0cxTzuk
nrSZ2R5HHbpKSVMvjuPAlMOq3XexuErh26HwC3/ZlhmShwFJOPfPON6mTlKb+lGtf2J+McSixov8
Hom6VAaGf6Ww8hZyq8X7exb+KpOCCvGwRXHueJDkSFj77B6bpOnSMLVdfVwdv4477KlJXggWs2iH
gbdG4otG7nbx8K5oicbO4jv4eJ2XlrdX8131i4z0dIlSUqZDOBbm+YNFZAs3v1a4NdPw7xJsE2xV
NJQu5PNV8/ik5Gb2PpJBdLhfe74cGeTx+gVk75F4H5r4BF55970vddtl4JccvFKPg6tn89FyD8GX
ltLesFX7tSXvn3tOcPurJg/sU+TUCeol3z2GhteNv92g4B2D/esWcrH9CI7UMREbpe/Ep1wb6tEe
6o5VcG+ZxKy3yNtrkSMecgV5u6UPxMdS4V8b7NW1i0eHad2UxfEnFKG1s7jcFdL7+5rryHx5Pjkf
SMxaS/t/sGom2c/mkX7PNvf6NC40lhFaqTj7TArfPmlyprpU58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6""")
def toto(self):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrLLy1WSC1JLVZIVCjJL8nnstGHSNjog9UBAGolDzo=""")
def p404(self):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04zIxMFFIScwrVihJVEhLTE5VUOSy0YdI2eiDVQIAZBgOeA==""")
def decompress_img(self,img):
img = zlib.decompress(base64.decodestring(img))
return img
def decompress_html(self,html) :
page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
page+=zlib.decompress(base64.decodestring(html))
commands = self.balisep.findall(page)
print commands
for c in commands :
command = c.replace("<? ","")
command = c.replace("<?","")
command = command.replace(" ?>","")
command = command.replace("?>","")
print command
with stdoutIO() as s:
exec(command)
page = page.replace(c,s.getvalue())
return page
class Serverhttp(SocketServer.BaseRequestHandler):
def handle(self):
self.Pages = Pages()
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
self.data = self.request.recv(1024)
socket = self.request
print "%s wrote:" % self.client_address[0]
self.data = self.traitement(self.data)
socket.sendto(self.data, self.client_address)
def traitement(self,data):
url = self.POST.findall(data)
url = self.GET.findall(data)
url = url[0].replace("GET","")
url = url.replace("POST","")
url = url.replace("HTTP","")
url = url.replace(" ","")
url = re.sub(r"^/","",url)
url = re.sub(r"\.","",url)
if url != "":
urls = url.split("/")
if len(urls) != 0 :
print urls
url = urls[0]
print "url %s"%url
if url == "" :
return self.Pages.root()
elif url in dir(self.Pages) and url != "":
return getattr(self.Pages,url)()
else :
return self.Pages.p404()
def serve_thread(host, port):
if port == 4242 :
server = SocketServer.TCPServer((host, port), Serverhttp,bind_and_activate=True)
elif port == 25 :
server = SocketServer.TCPServer((host, port), Serversmtp,bind_and_activate=True)
server.serve_forever()
if __name__ == "__main__":
threading.Thread(target=serve_thread,args=('localhost', 4242)).start()
threading.Thread(target=serve_thread,args=('localhost', 25)).start()
print "toto"
| Python Servers fighting each others with sockets | I try to make two servers in a file, but they are fighting each other visibly
have anyone an idea to make them peace ?
here is my code :
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
from threading import Thread
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow :
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam
"""
def sendmail(exp,dest,msg):
server = dest.split("@")[1]
s = smtplib.SMTP("localhost")
s.sendmail(exp,dest,msg)
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Serversmtp(Thread):
def __init__self(self):
Thread.__init__(self)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 25)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
class Pages :
def root(self,cgi=None):
return """eNqtVV1zqkgQfedX3MrrbNVREBnu5ubWCCoajPiRaHyTxEGNiAKC8uu3B7Nb+7JvO1QNNAOnT5/u
6Xnc5vHhSXsMk8/bk5bv7tdjmNK7XRz9yNKPXw+f63z9cxevow12H8mf4TrbtFt/CCE6QnRFl2Z1
H4hOoh57EU2OmsRETQPx9/p/D+3fhhXMLRhVrw07yC/ANPSuaOi6BTavihB2UZiwrW1D2sNNp8KL
lwhUNheFLaRwoQVeJtDotUXAa0AUlYUmMwzw0YlV6KVeievixiUPM8zhndMrOexaBWhYyPn5hKqn
C3BLi0oPQWvgojJtAmSbyMXE+BLEIOMFD5N8j65/NFDeTAIMcunDtXxycKnsgBdnJsFxVMCWZhf2
83ZqYPz+Tgz7PVFwvlWAA+GgaloiQINhj5d2OELpNCxw5yotOFlgoYyZXXBxvqSYpW6oESKDokxr
b6vuAdVsSAyt/cRFUDsYdzqSMznx6CMDsN0TB29lIwJMXUkOmi1ykF58aM/n4wL2MeOKLYG2xvsl
KtZ3JTe/SNRgUJIE+pAYs61ykHRJAsc6FSTEpRaOwV6WrGClZmz2OGTYgKWVjftgqNrQ9Xgm+XlP
jMbDEWXtMiHG5q70yUFE9q0nAjaezXwc31otWEOmvRUQX30LVp4GKjuQsNW9DT+FfkmmBc8VYDB8
V4BzJcFXqSTgZOvPZNtbiiA5fB01tKdvXsA2s2iPuBtNAS8xFLnCgjmutmj210MCPNAP49UHJeWy
pJBbtW0OyNYDIbmtGGvjAZVBe7voSfYxv7o4xbYDq73bBncNmYqbH9cFuPykH15WVJfVZkWMjJiy
HgwnHQr5lQBb2r6mnNGLtickk8udRDNtZxSqktDktBOMlEVgxk4vFLaBONz1cLs5KuQ4CjA+EWq1
WWhK1AM9j09dAmSkie1sqZCtjRfW2Sigc0pSvigTEvaVRDeXE5JgxMz7Oguz1REDT3xqhPimRDwo
D6bK2nroSJ6v5inc2+W5ri2gTnTjHJMEB3KI55WYo3iLHPDdZCHvjKlo98AtOl3B+/0PH93Z+opr
N8oL3uuOKgjhb1GKTlMSGlU+UJECJh8D/eXEx63/ToDTtSgw1vYHeRe5Hvbk1TbQEW5DAZDyrggM
AvQqsoUpyc7T728L2jpMD505AVJE3I5JM3QWVNmNM3PxnTy1taZfYYSyK5ikbkJsxMQzUY4EV91l
Q8UpXFm3jeDePS6Dl4lGGiwJcPROaS/6A2Lvx8Z3WTQ/5zrKZGSCABTD0mM1Y+VAhiqCjGyn9d2+
SDPqX8wPq4DFyxtV8mvZhd3PtlRYSlQLxKhKUCrAzyVE5LdVyATofEugK9ui7lF32oja8f8x/mnb
d8Bfvx6e7kfHb+2U7o75j4c8yZMH9qDePmi/nzTtEfej5hH1yfMXx7rT9A=="""
def favico(self):
return """eNqdk39MVWUYx99zDrZkJJc/dGtqsVZKFmttFhcuF0wXC1bTZmq0qVuWa8t+/NXPW1MQCk3FMBKs
LNauoq6AAr2zsFLLHAN1YQXJryzJewXuhV29HO759JyX//uj9933vOe8e7/f5/k+73OUMmR6PEqe
meq5FKXmKKWyBLIlO9P7/zUiEzaB02GWt43ycHOUx2St6YwTtxP0DZ6n+LV5LH5DURgwWRJQ5L+p
eEi+Xa4zZbP+aD9pByLMaR5jdkuUuV9NcNuhKIFTI4DD0bON3P+Kha/coLDMouAtRYHwl72u6IvE
mNvwG57QddJCUdJbY6S3jGmN+w5fYTwhCnackor55FZK3AqTfFmXbDbxSx4T9g1ygh2or0cxTzuk
nrSZ2R5HHbpKSVMvjuPAlMOq3XexuErh26HwC3/ZlhmShwFJOPfPON6mTlKb+lGtf2J+McSixov8
Hom6VAaGf6Ww8hZyq8X7exb+KpOCCvGwRXHueJDkSFj77B6bpOnSMLVdfVwdv4477KlJXggWs2iH
gbdG4otG7nbx8K5oicbO4jv4eJ2XlrdX8131i4z0dIlSUqZDOBbm+YNFZAs3v1a4NdPw7xJsE2xV
NJQu5PNV8/ik5Gb2PpJBdLhfe74cGeTx+gVk75F4H5r4BF55970vddtl4JccvFKPg6tn89FyD8GX
ltLesFX7tSXvn3tOcPurJg/sU+TUCeol3z2GhteNv92g4B2D/esWcrH9CI7UMREbpe/Ep1wb6tEe
6o5VcG+ZxKy3yNtrkSMecgV5u6UPxMdS4V8b7NW1i0eHad2UxfEnFKG1s7jcFdL7+5rryHx5Pjkf
SMxaS/t/sGom2c/mkX7PNvf6NC40lhFaqTj7TArfPmlyprpU58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6"""
class Serverhttp(Thread):
def __init__(self):
Thread.__init__(self)
self.Pages = Pages()
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
self.balisep = re.compile("<\?.*\?>",re.DOTALL)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 41000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
def decompress_img(self,img):
img = zlib.decompress(base64.decodestring(img))
return img
def decompress_html(self,html) :
page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
page+=zlib.decompress(base64.decodestring(html))
commands = self.balisep.findall(page)
print commands
for c in commands :
command = c.replace("<? ","")
command = c.replace("<?","")
command = command.replace(" ?>","")
command = command.replace("?>","")
print command
with stdoutIO() as s:
exec(command)
page = page.replace(c,s.getvalue())
return page
def traitement(self,data):
url = self.POST.findall(data)
print url
print len(url)
url = self.GET.findall(data)
print url
url = url[0].replace("GET","")
url = url.replace("POST","")
url = url.replace("HTTP","")
url = url.replace(" ","")
print url
if url == "/favicon.ico":
return self.decompress_img(self.Pages.favico())
else :
return self.decompress_html(self.Pages.root())
if __name__ == "__main__":
swww = Serverhttp()
swww.start()
ssmtp = Serversmtp()
ssmtp.start()
sendmail("test@test.com","b@gmail.com","hello")
print "toto"
Regards and thanks all people
| [
"it was better to use : SocketServer.BaseRequestHandler with handler\nand one for each server :\nas seen here :\n# MetaProject v 0.21\n# -*- coding: utf-8 -*-\nimport socket\nimport sys\nimport re\nimport base64\nimport binascii\nimport time\nimport zlib\nimport sys\nimport StringIO\nimport contextlib\nimport smtpl... | [
0
] | [] | [] | [
"asynchronous",
"port",
"python",
"sockets"
] | stackoverflow_0003909964_asynchronous_port_python_sockets.txt |
Q:
How can fractional number expressions be parsed using pyparsing?
We've just started to kick the tires pyparsing and like it so far, but we've been unable to get it to help us parse fractional number strings to turn them into numeric data types.
For example, if a column value in a database table contained the string:
1 1/2
We'd like some way to convert it into the numeric python equivalent:
1.5
We'd like to make a parser that doesn't care whether the numbers in the fraction are integer or real. For example, we'd like:
1.0 1.0/2.0
...to still translate to:
1.5
Essentially we'd like a parser conceptually to do the following:
"1 1/2" = 1 + 0.5 = 1.5
The following example code seems to get us close...
http://pyparsing.wikispaces.com/file/view/parsePythonValue.py
...but not close enough to make headway. All our tests to make a fractional number handler only return the first part of the expression (1). Tips? Hints? Timely Wisdom? :)
A:
Since you cite some tests, it sounds like you've at least taken a stab at the problem. I assume you've already defined a single number, which can be integer or real - doesn't matter, you are converting everything to float anyway - and a fraction of two numbers, probably something like this:
from pyparsing import Regex, Optional
number = Regex(r"\d+(\.\d*)?").setParseAction(lambda t: float(t[0]))
fraction = number("numerator") + "/" + number("denominator")
fraction.setParseAction(lambda t: t.numerator / t.denominator)
(Note the use of parse actions, which do the floating point conversion and fractional division right at parse time. I prefer to do this while parsing, when I know something is a number or a fraction or whatever, instead of coming back later and sifting through a bunch of fragmented strings, trying to recreate the recognition logic that the parser has already done.)
Here are the test cases I composed for your problem, made up of a whole number, a fraction, and a whole number and fraction, using both integers and reals:
tests = """\
1
1.0
1/2
1.0/2.0
1 1/2
1.0 1/2
1.0 1.0/2.0""".splitlines()
for t in tests:
print t, fractExpr.parseString(t)
The last step is how to define a fractional expression that can be a single number, a fraction, or a single number and a fraction.
Since pyparsing is left-to-right, it does not do the same kind of backtracking like regexen do. So this expression wont work so well:
fractExpr = Optional(number) + Optional(fraction)
To sum together the numeric values that might come from the number and fraction parts, add this parse action:
fractExpr.setParseAction(lambda t: sum(t))
Our tests print out:
1 [1.0]
1.0 [1.0]
1/2 [1.0]
1.0/2.0 [1.0]
1 1/2 [1.5]
1.0 1/2 [1.5]
1.0 1.0/2.0 [1.5]
For the test case 1/2, containing just a fraction by itself, the leading numerator matches the Optional(number) term, but that leaves us just with "/2", which doesn't match the Optional(fraction) - fortunately, since the second term is optional, this "passes", but it's not really doing what we want.
We need to make fractExpr a little smarter, and have it look first for a lone fraction, since there is this potential confusion between a lone number and the leading numerator of a fraction. The easiest way to do this is to make fractExpr read:
fractExpr = fraction | number + Optional(fraction)
Now with this change, our tests come out better:
1 [1.0]
1.0 [1.0]
1/2 [0.5]
1.0/2.0 [0.5]
1 1/2 [1.5]
1.0 1/2 [1.5]
1.0 1.0/2.0 [1.5]
There are a couple of classic pitfalls with pyparsing, and this is one of them. Just remember that pyparsing only does the lookahead that you tell it to, otherwise it is just straight left-to-right parsing.
A:
Not precisely what you're looking for, but...
>>> import fractions
>>> txt= "1 1/2"
>>> sum( map( fractions.Fraction, txt.split() ) )
Fraction(3, 2)
>>> float(_)
1.5
A:
This recipe might be helpful:
http://gist.github.com/361586
Look around line 39:
mixed = Combine(numeral + fraction, adjacent=False, joinString=' ')
A:
This is kind of double with S. Lott, but here is it anyway:
from fractions import Fraction
print sum(Fraction(part) for part in '1 1/2'.split())
Dealing with float 'integers' would be quite convoluted, though:
from fractions import Fraction
clean = '1.0 1.0/2.0'.replace('.0 ',' ').replace('.0/', '/').rstrip('0.').split()
print(clean)
print(sum(Fraction(part) for part in clean))
And other poster's examples, plus one with / with whitespace:
from fractions import Fraction
tests = """\
1
1.0
1/2
1.0/2.0
1 1/2
1.0 1/2
1.0 1.0/2.0
1.0 1.0 / 2.0
""".splitlines()
for t in tests:
clean = t.replace('.0 ',' ').replace('.0/', '/').rstrip('0.').split()
value = sum(Fraction(part) for part in clean)
print('%s -> %s, %s = %f' % (t, clean, value, float(value)))
| How can fractional number expressions be parsed using pyparsing? | We've just started to kick the tires pyparsing and like it so far, but we've been unable to get it to help us parse fractional number strings to turn them into numeric data types.
For example, if a column value in a database table contained the string:
1 1/2
We'd like some way to convert it into the numeric python equivalent:
1.5
We'd like to make a parser that doesn't care whether the numbers in the fraction are integer or real. For example, we'd like:
1.0 1.0/2.0
...to still translate to:
1.5
Essentially we'd like a parser conceptually to do the following:
"1 1/2" = 1 + 0.5 = 1.5
The following example code seems to get us close...
http://pyparsing.wikispaces.com/file/view/parsePythonValue.py
...but not close enough to make headway. All our tests to make a fractional number handler only return the first part of the expression (1). Tips? Hints? Timely Wisdom? :)
| [
"Since you cite some tests, it sounds like you've at least taken a stab at the problem. I assume you've already defined a single number, which can be integer or real - doesn't matter, you are converting everything to float anyway - and a fraction of two numbers, probably something like this:\nfrom pyparsing import... | [
8,
3,
2,
1
] | [] | [] | [
"dsl",
"fractions",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0003911824_dsl_fractions_parsing_pyparsing_python.txt |
Q:
How to decode string to use with Google Language Detection API?
I want to use Google Language Detection API in my app to detect language of url parameter. For example user requests url
http://myapp.com/q?Это тест
and gets message "Russian". I do it this way:
def get(self):
url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+self.request.query
try:
data = json.loads(urllib2.urlopen(url).read())
self.response.out.write('<html><body>' + data["responseData"]["language"] +'</body></html>')
except urllib2.HTTPError, e:
self.response.out.write( "HTTP error: %d" % e.code )
except urllib2.URLError, e:
self.response.out.write( "Network error: %s" % e.reason.args[1])
but always get "English" as result because url is encoded in
http://myapp.com/q?%DD%F2%EE%20%F2%E5%F1%F2
I've tried urllib.quote , urllib.urlencode with no luck.
How I have to decode this url for Google Api?
A:
Maybe urllib.unquote is what you are looking for:
>>> from urllib import unquote
>>> unquote("%DD%F2%EE%20%F2%E5%F1%F2")
This gives you a string in which the characters are in whatever encoding that you've used in the URL. If you want to recode it to a different encoding (say, UTF-8), you have to create a unicode object first and then use the encode method of the unicode object to recode it:
>>> from urllib import unquote, quote
>>> import json, urllib2, pprint
>>> decoded = unicode(unquote("%DD%F2%EE%20%F2%E5%F1%F2"), "windows-1251")
>>> print decoded
Это тест
>>> recoded = decoded.encode("utf-8")
At this point, we have an UTF-8 encoded string, but this is still not suitable to be passed on to the Google Language Detection API:
>>> recoded
'\xd0\xad\xd1\x82\xd0\xbe \xd1\x82\xd0\xb5\xd1\x81\xd1\x82'
Since you want to include this string in a URL as a query argument, you have to encode it using urllib.quote:
>>> url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=%s" % quote(recoded)
>>> data = json.loads(urllib2.urlopen(url).read())
>>> pprint.pprint(data)
{u'responseData': {u'confidence': 0.094033934,
u'isReliable': False,
u'language': u'ru'},
u'responseDetails': None,
u'responseStatus': 200}
| How to decode string to use with Google Language Detection API? | I want to use Google Language Detection API in my app to detect language of url parameter. For example user requests url
http://myapp.com/q?Это тест
and gets message "Russian". I do it this way:
def get(self):
url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+self.request.query
try:
data = json.loads(urllib2.urlopen(url).read())
self.response.out.write('<html><body>' + data["responseData"]["language"] +'</body></html>')
except urllib2.HTTPError, e:
self.response.out.write( "HTTP error: %d" % e.code )
except urllib2.URLError, e:
self.response.out.write( "Network error: %s" % e.reason.args[1])
but always get "English" as result because url is encoded in
http://myapp.com/q?%DD%F2%EE%20%F2%E5%F1%F2
I've tried urllib.quote , urllib.urlencode with no luck.
How I have to decode this url for Google Api?
| [
"Maybe urllib.unquote is what you are looking for:\n>>> from urllib import unquote\n>>> unquote(\"%DD%F2%EE%20%F2%E5%F1%F2\")\n\nThis gives you a string in which the characters are in whatever encoding that you've used in the URL. If you want to recode it to a different encoding (say, UTF-8), you have to create a u... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"urldecode"
] | stackoverflow_0003914803_google_app_engine_python_urldecode.txt |
Q:
Length of arguments of Python function?
Possible Duplicate:
How to find out the arity of a method in Python
For example I have declared a function:
def sum(a,b,c):
return a + b + c
I want to get length of arguments of "sum" function.
somethig like this: some_function(sum) to returned 3
How can it be done in Python?
Update:
I asked this question because I want to write a function that accepts another function as a parameter and arguments to pass it.
def funct(anotherFunct, **args):
and I need to validate:
if(len(args) != anotherFuct.func_code.co_argcount):
return "error"
A:
The inspect module is your friend; specifically inspect.getargspec which gives you information about a function's arguments:
>>> def sum(a,b,c):
... return a + b + c
...
>>> import inspect
>>> argspec = inspect.getargspec(sum)
>>> print len(argspec.args)
3
argspec also contains details of optional arguments and keyword arguments, which in your case you don't have, but it's worth knowing about:
>>> print argspec
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)
A:
If your method name is sum then sum.func_code.co_argcount will give you number of arguments.
A:
import inspect
print len(inspect.getargspec(sum)[0])
| Length of arguments of Python function? |
Possible Duplicate:
How to find out the arity of a method in Python
For example I have declared a function:
def sum(a,b,c):
return a + b + c
I want to get length of arguments of "sum" function.
somethig like this: some_function(sum) to returned 3
How can it be done in Python?
Update:
I asked this question because I want to write a function that accepts another function as a parameter and arguments to pass it.
def funct(anotherFunct, **args):
and I need to validate:
if(len(args) != anotherFuct.func_code.co_argcount):
return "error"
| [
"The inspect module is your friend; specifically inspect.getargspec which gives you information about a function's arguments:\n>>> def sum(a,b,c):\n... return a + b + c\n...\n>>> import inspect\n>>> argspec = inspect.getargspec(sum)\n>>> print len(argspec.args)\n3\n\nargspec also contains details of optional ar... | [
16,
5,
3
] | [] | [] | [
"arguments",
"function",
"parameters",
"python"
] | stackoverflow_0003913963_arguments_function_parameters_python.txt |
Q:
Dynamically creating classes - Python
I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form class.
By "dynamically" I intend to create a class based on configuration provided by a user.
e.g.
I want a class named CommentForm which should subclass the Form class.
The class should have a list of chosen attributes.
....in this case
name = forms.CharField()
comment = forms.CharField(widget=forms.Textarea())
Any useful tips? :)
A:
You can create classes on the fly by calling the type built-in, passing appropriate arguments along, like:
CommentForm = type("CommentForm", (Form,), {
'name': forms.CharField(),
...
})
It works with new-style classes. I am not sure, whether this would also work with old-style classes.
A:
Classes can be defined almost anywhere.
def newclass(val):
class C(object):
def __str__(self):
return str(val)
return C
MyClass = newclass(5)
m = MyClass()
print str(m)
| Dynamically creating classes - Python | I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form class.
By "dynamically" I intend to create a class based on configuration provided by a user.
e.g.
I want a class named CommentForm which should subclass the Form class.
The class should have a list of chosen attributes.
....in this case
name = forms.CharField()
comment = forms.CharField(widget=forms.Textarea())
Any useful tips? :)
| [
"You can create classes on the fly by calling the type built-in, passing appropriate arguments along, like:\nCommentForm = type(\"CommentForm\", (Form,), { \n 'name': forms.CharField(),\n ...\n})\n\nIt works with new-style classes. I am not sure, whether this would also work with old-style classes.\n",
"Cla... | [
35,
14
] | [] | [] | [
"class",
"django",
"dynamic",
"forms",
"python"
] | stackoverflow_0003915024_class_django_dynamic_forms_python.txt |
Q:
Twisted HTTP Proxy Channel set to None on LostConnection but loseConnection hasn't been called yet
Ok I have been writing a proxy to take http GET requests and translate them into HTTP POST requests (because a lot of media players for python only support GET). So I know am working on caching those results that way I only download a url once, I moved a lot of code from the super class to the sub class and changed it so that I could send the same thing to multiple server connections (e.g if a server connection was made I would just attach it to a download instance if available).
Anyways, it mostly works except the last part for some reason the http channel is set to None before I call loseConnection (this is without any errors like the internet going out etc), this results in an error that a None object has no attribute transport that I am calling loseConnection on.
Here is the code
self.connectionDone = True
print self.producers
for p in self.producers:
print p
print p.channel
print dir(p)
p.channel.transport.loseConnection()
self.transport.loseConnection()
and the traceback of self.channel being set to none (traceback module's print_stack on each setattr call)
Note: Look at the last few lines, I think that is where the problem is.
File "Sharky.py", line 581, in <module>
reactor.run()
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\wxreactor.py", line 145, in run
self.wxapp.MainLoop()
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 8007, in MainLoop
wx.PyApp.MainLoop(self)
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7303, in MainLoop
return _core_.PyApp_MainLoop(*args, **kwargs)
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 14640, in <lambda>
lambda event: event.callable(*event.args, **event.kw) )
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 243, in _interleave
getattr(self, '_process_' + msg)(*args)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 209, in _process_Notify
_logrun(selectable, _drdw, selectable, method, dct)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 59, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 37, in callWithContext
return func(*args,**kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 303, in _doReadOrWrite
self._disconnectSelectable(selectable, why, method == "doRead")
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\posixbase.py", line 253, in _disconnectSelectable
selectable.connectionLost(f)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py", line 519, in connectionLost
protocol.connectionLost(reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", line 1725, in connectionLost
request.connectionLost(reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", line 1287, in connectionLost
self.channel = None
File "C:\Documents and Settings\Admin\My Documents\Mercurial\sharky\ProxyServer.py", line 172, in __setattr__
traceback.print_stack()
This is the none attribute exception I get
Traceback (most recent call last):
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7303, in MainLoop
return _core_.PyApp_MainLoop(*args, **kwargs)
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 14640, in <lambda>
lambda event: event.callable(*event.args, **event.kw) )
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 243, in _interleave
getattr(self, '_process_' + msg)(*args)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 209, in _process_Notify
_logrun(selectable, _drdw, selectable, method, dct)
--- <exception caught here> ---
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 59, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 37, in callWithContext
return func(*args,**kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 303, in _doReadOrWrite
self._disconnectSelectable(selectable, why, method == "doRead")
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\posixbase.py", line 253, in _disconnectSelectable
selectable.connectionLost(f)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py", line 677, in connectionLost
Connection.connectionLost(self, reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py", line 519, in connectionLost
protocol.connectionLost(reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", line 489, in connectionLost
self.handleResponseEnd()
File "C:\Documents and Settings\Admin\My Documents\Mercurial\sharky\ProxyServer.py", line 103, in handleResponseEnd
p.channel.transport.loseConnection()
exceptions.AttributeError: 'NoneType' object has no attribute 'transport'
A:
Connections may be lost without the internet going out. All it takes is for one side of the connection to call shutdown() or close(). Have you ruled that out? And even if you have, for the code to be correct, it needs to handle that possibility anyway, because it might happen at some other time. See Request.notifyFinish.
| Twisted HTTP Proxy Channel set to None on LostConnection but loseConnection hasn't been called yet | Ok I have been writing a proxy to take http GET requests and translate them into HTTP POST requests (because a lot of media players for python only support GET). So I know am working on caching those results that way I only download a url once, I moved a lot of code from the super class to the sub class and changed it so that I could send the same thing to multiple server connections (e.g if a server connection was made I would just attach it to a download instance if available).
Anyways, it mostly works except the last part for some reason the http channel is set to None before I call loseConnection (this is without any errors like the internet going out etc), this results in an error that a None object has no attribute transport that I am calling loseConnection on.
Here is the code
self.connectionDone = True
print self.producers
for p in self.producers:
print p
print p.channel
print dir(p)
p.channel.transport.loseConnection()
self.transport.loseConnection()
and the traceback of self.channel being set to none (traceback module's print_stack on each setattr call)
Note: Look at the last few lines, I think that is where the problem is.
File "Sharky.py", line 581, in <module>
reactor.run()
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\wxreactor.py", line 145, in run
self.wxapp.MainLoop()
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 8007, in MainLoop
wx.PyApp.MainLoop(self)
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7303, in MainLoop
return _core_.PyApp_MainLoop(*args, **kwargs)
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 14640, in <lambda>
lambda event: event.callable(*event.args, **event.kw) )
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 243, in _interleave
getattr(self, '_process_' + msg)(*args)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 209, in _process_Notify
_logrun(selectable, _drdw, selectable, method, dct)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 59, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 37, in callWithContext
return func(*args,**kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 303, in _doReadOrWrite
self._disconnectSelectable(selectable, why, method == "doRead")
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\posixbase.py", line 253, in _disconnectSelectable
selectable.connectionLost(f)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py", line 519, in connectionLost
protocol.connectionLost(reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", line 1725, in connectionLost
request.connectionLost(reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", line 1287, in connectionLost
self.channel = None
File "C:\Documents and Settings\Admin\My Documents\Mercurial\sharky\ProxyServer.py", line 172, in __setattr__
traceback.print_stack()
This is the none attribute exception I get
Traceback (most recent call last):
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7303, in MainLoop
return _core_.PyApp_MainLoop(*args, **kwargs)
File "C:\Program Files\Python 2.6.2\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 14640, in <lambda>
lambda event: event.callable(*event.args, **event.kw) )
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 243, in _interleave
getattr(self, '_process_' + msg)(*args)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 209, in _process_Notify
_logrun(selectable, _drdw, selectable, method, dct)
--- <exception caught here> ---
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 59, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.py", line 37, in callWithContext
return func(*args,**kw)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\_threadedselect.py", line 303, in _doReadOrWrite
self._disconnectSelectable(selectable, why, method == "doRead")
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\posixbase.py", line 253, in _disconnectSelectable
selectable.connectionLost(f)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py", line 677, in connectionLost
Connection.connectionLost(self, reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py", line 519, in connectionLost
protocol.connectionLost(reason)
File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", line 489, in connectionLost
self.handleResponseEnd()
File "C:\Documents and Settings\Admin\My Documents\Mercurial\sharky\ProxyServer.py", line 103, in handleResponseEnd
p.channel.transport.loseConnection()
exceptions.AttributeError: 'NoneType' object has no attribute 'transport'
| [
"Connections may be lost without the internet going out. All it takes is for one side of the connection to call shutdown() or close(). Have you ruled that out? And even if you have, for the code to be correct, it needs to handle that possibility anyway, because it might happen at some other time. See Request.no... | [
1
] | [] | [] | [
"python",
"twisted",
"twisted.web"
] | stackoverflow_0003911202_python_twisted_twisted.web.txt |
Q:
Advice on which language to use
I'm trying to create a web application which will get input from system.
What this application should do is to listen what happens when some shell scripts are executing and reporting the status trough web.
An example :
I'm copying thousands of records with shell script, and while this is still executing I'd like pass the current status of the script to the web interface. From shell script side I could echo something like "The files are being copied please wait for it to finnish".
Using which programming language from shell side would be the easiest way to pass this to the web interface? I intended to use JSP/JAVA for web.
Is this even the right way to think about this? Every suggestion is welcome
EDIT
Would something like http://nodejs.org/ be useful for this?
A:
I'd use a named pipe (FIFO) instead. You simply write your output to the pipe and let the application read it. I'm not sure if there is any other way to get a more live system than this.
I'd recommend Perl as the back-end.
EDIT:
named pipes are a special type of files on UNIX. The abbreviation FIFO stands for "First In First Out". On LINUX Journal you can find an interesting read about named pipes.
Perl is a very powerful scripting language with many ready-to-use modules which you can find on http://cpan.org. You can find some answers here on SO about how/where to start learning Perl.
A:
The Web part of your application can easily read a file or a database, so you just need to make sure that your shell scripts are outputting something for your Java code to update.
For example, if you run your shell script like this
./myscript.sh > mylog.log
Then in your Java code (note that you should not have logic in your JSP), you can read in the file to determine the status of the update, and output the result to your JSP.
It would be better to read the data in from a database, but that would involve you changing your shell script to output the data to a database.
A:
You could put shell script output to some storage on server. And use AJAX on the web page to poll the server and get updates from that storage to the page.
If you will decide to use JSF for web page creation I can recommend "a4j:poll" component from ajax2jsf library. It is very simple and straightforward. Very easy way to poll server from the web page.
A:
Writing to log file would be the simplest solution. And in programming, simple often means good.
If you really need very fast/realtime system, you should probably make these logs a database.
As for language, use what you like best. They all do support SQLite, including bash.
A:
If I understand your question correctly you want to display a web page on a client machine that reports the status of a long running task on a server machine. If that is the case then you need to focus on something called AJAX IMO.
For what it is worth the simplest and easiest to understand implementation of AJAX that I know of is Apache Wicket.
| Advice on which language to use | I'm trying to create a web application which will get input from system.
What this application should do is to listen what happens when some shell scripts are executing and reporting the status trough web.
An example :
I'm copying thousands of records with shell script, and while this is still executing I'd like pass the current status of the script to the web interface. From shell script side I could echo something like "The files are being copied please wait for it to finnish".
Using which programming language from shell side would be the easiest way to pass this to the web interface? I intended to use JSP/JAVA for web.
Is this even the right way to think about this? Every suggestion is welcome
EDIT
Would something like http://nodejs.org/ be useful for this?
| [
"I'd use a named pipe (FIFO) instead. You simply write your output to the pipe and let the application read it. I'm not sure if there is any other way to get a more live system than this.\nI'd recommend Perl as the back-end.\nEDIT: \nnamed pipes are a special type of files on UNIX. The abbreviation FIFO stands for ... | [
5,
2,
0,
0,
0
] | [] | [] | [
"java",
"perl",
"python",
"shell",
"system"
] | stackoverflow_0003914615_java_perl_python_shell_system.txt |
Q:
Developing and using the same Python on the same computer
I'm developing a Python utility module to help with file downloads, archives, etc. I have a project set up in a virtual environment along with my unit tests. When I want to use this module on the same computer (essentially as "Production"), I move the files to the mymodule directory in the ~/dev/modules/mymodule
I keep all 3rd-party modules under ~/dev/modules/contrib. This contrib path is on my PYTHONPATH, but mymodule is NOT because I've noticed that if mymodule is on my PYTHONPATH, my unit tests cannot distinguish between the "Development" version and the "Production" version. But now if I want to use this common utility module, I have to manually add it to the PYTHONPATH.
This works, but I'm sure there's a better, more automated way.
What is the best way to have a Development and Production module on the same computer? For instance, is there a way to set PYTHONPATH dynamically?
A:
I'm guessing by virtual environment you mean the virtualenv package?
http://pypi.python.org/pypi/virtualenv
What I'd try (and apologies if I've not understood the question right) is:
Keep the source somewhere that isn't referenced by PYTHONPATH (e.g. ~/projects/myproject)
Write a simple setuptools or distutils script for installing it (see Python distutils - does anyone know how to use it?)
Use the virtualenv package to create a dev virtual environment with the --no-site-packages option - this way your "dev" version won't see any packages installed in the default python installation.
(Also make sure your PYTHONPATH doesn't have any of your source directories)
Then, for testing:
Activate dev virtual environment
Run install script, (usually something like python setup.py build install). Your package ends up in /path/to/dev_virtualenv/lib/python2.x/site-packages/
Test, break, fix, repeat
And, for production:
Make sure dev virtualenv isn't activated
Run install script
All good to go, the "dev" version is hidden away in a virtual environment that production can't see...
...And there's no (direct) messing around with PYTHONPATH
That said, I write this with the confidence of someone who's not actually tried setting using virtualenv in anger and the hope I've vaguely understood your question... ;)
A:
You can add/modify python paths at sys.path, just make sure that the first path is the current directory ".", because some third-party modules rely on importing from the directory of the current module.
More information on python paths:
http://djangotricks.blogspot.com/2008/09/note-on-python-paths.html
A:
You could set the PYTHONPATH as a global environment variable pointing to your Production code, and then in any shell in which you want to use the Development code, change the PYTHONPATH to point to that code.
(Is that too simplistic? Have I missed something?)
| Developing and using the same Python on the same computer | I'm developing a Python utility module to help with file downloads, archives, etc. I have a project set up in a virtual environment along with my unit tests. When I want to use this module on the same computer (essentially as "Production"), I move the files to the mymodule directory in the ~/dev/modules/mymodule
I keep all 3rd-party modules under ~/dev/modules/contrib. This contrib path is on my PYTHONPATH, but mymodule is NOT because I've noticed that if mymodule is on my PYTHONPATH, my unit tests cannot distinguish between the "Development" version and the "Production" version. But now if I want to use this common utility module, I have to manually add it to the PYTHONPATH.
This works, but I'm sure there's a better, more automated way.
What is the best way to have a Development and Production module on the same computer? For instance, is there a way to set PYTHONPATH dynamically?
| [
"I'm guessing by virtual environment you mean the virtualenv package?\nhttp://pypi.python.org/pypi/virtualenv\nWhat I'd try (and apologies if I've not understood the question right) is:\n\nKeep the source somewhere that isn't referenced by PYTHONPATH (e.g. ~/projects/myproject)\nWrite a simple setuptools or distuti... | [
1,
1,
0
] | [] | [] | [
"module",
"packaging",
"python",
"pythonpath"
] | stackoverflow_0003914289_module_packaging_python_pythonpath.txt |
Q:
How to copy a variable number of elements in a list to a uniform list and store in MySQL using Python the most efficient way?
This is a sample list (each line has variable elements) :
['1', 'Tech', 'Code']
['2', 'Edu']
['3', 'Money', 'Sum', '176']
I have to insert this into a MySQL table which has 4 columns (max num. of elements in a value in a list).
How to do this efficiently? I have a feeling my solution is the least efficient!
Here is my solution :
for eachval in mylistings: #mylistings has the sample list elements described above
mylen = len(eachval)
defaultlist = [None]*4 #reset defaultlist to 'None' to handle variable no. of columns
ctr = 0
for myoneval in mylistingline:
defaultlist[ctr] = myoneval
ctr += 1
for finalval in defaultlist: #finally inserting them into a MySQL table
cursor.execute("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", (finalval[0], finalval[1], finalval[2], finalval[3]))
A:
How about this?
for line in mylistings:
out = line + [None] * (4 - len(line)) # pad the list with None to 4 elements
cursor.execute("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", out)
A:
You should use executemany to speed things up on the database side. Also, you can cache the padding list so you don't have to create it every time:
values = []
padding = [None] * 4
for line in mylistings:
values.append((line + padding)[:4])
cursor.executemany("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", values)
You can also use itertools so that you don't construct the padded list at all:
from itertools import chain, islice
values = []
padding = [None] * 4
for line in mylistings:
values.append(tuple(islice(chain(line, padding), 4)))
cursor.executemany("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", values)
From my testing, using tuple(islice(chain(line, padding), 4)) is about 5% faster 50% slower than (line + padding)[:4].
EDIT: I forgot that for string substitution you need tuples or lists, and adding the tuple wrapper slowed the second solution down significantly. But the first one still works!
| How to copy a variable number of elements in a list to a uniform list and store in MySQL using Python the most efficient way? | This is a sample list (each line has variable elements) :
['1', 'Tech', 'Code']
['2', 'Edu']
['3', 'Money', 'Sum', '176']
I have to insert this into a MySQL table which has 4 columns (max num. of elements in a value in a list).
How to do this efficiently? I have a feeling my solution is the least efficient!
Here is my solution :
for eachval in mylistings: #mylistings has the sample list elements described above
mylen = len(eachval)
defaultlist = [None]*4 #reset defaultlist to 'None' to handle variable no. of columns
ctr = 0
for myoneval in mylistingline:
defaultlist[ctr] = myoneval
ctr += 1
for finalval in defaultlist: #finally inserting them into a MySQL table
cursor.execute("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", (finalval[0], finalval[1], finalval[2], finalval[3]))
| [
"How about this?\nfor line in mylistings:\n out = line + [None] * (4 - len(line)) # pad the list with None to 4 elements\n cursor.execute(\"INSERT INTO LoadData VALUES (%s, %s, %s, %s)\", out)\n\n",
"You should use executemany to speed things up on the database side. Also, you can cache the padding list so ... | [
2,
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003915222_mysql_python.txt |
Q:
TKinter: I cannot see my left frame with a button inside
I cannot see my left frame with a button inside (I'm using TKinter).. This is my code:
#create window & frames
root = Tk()
root.title( "Medical Visualization" )
rootFrame = Frame(root)
rootFrame.pack( fill=BOTH, expand=1, side=TOP )
leftframe = Frame(root, width=100, bg="blue")
leftframe.pack(fill=X, expand=True)
button = Button(leftframe, text="Add Isosurface", fg="red")
button.pack( side = LEFT)
root.mainloop()
thanks
A:
I see it, and looking at the code I see nothing that would prevent it from being seen. Are you remembering to call root.mainloop? Your code snippet doesn't show you calling that method.
| TKinter: I cannot see my left frame with a button inside | I cannot see my left frame with a button inside (I'm using TKinter).. This is my code:
#create window & frames
root = Tk()
root.title( "Medical Visualization" )
rootFrame = Frame(root)
rootFrame.pack( fill=BOTH, expand=1, side=TOP )
leftframe = Frame(root, width=100, bg="blue")
leftframe.pack(fill=X, expand=True)
button = Button(leftframe, text="Add Isosurface", fg="red")
button.pack( side = LEFT)
root.mainloop()
thanks
| [
"I see it, and looking at the code I see nothing that would prevent it from being seen. Are you remembering to call root.mainloop? Your code snippet doesn't show you calling that method. \n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003915582_python_tkinter.txt |
Q:
Parsing PDF file using Regular expressions in Python
I am trying to parse some object elements from a PDF file using re module of Python. My goal is to parse each PDF object using a regular expression.
A PDF object example is the following:
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/Kids [ 3 0 R ]
/Count 1
>>
endobj
...
When I use "\d+\s\d+\sobj[\s,\S]*endobj" it doesn't work (it keeps parsing util last endobj is found). How can I modify regular expression in order to parse each object seperately (in other words the part from 1 0 obj until endobj)?
A:
If you are using only regex, it is easy to construct a PDF file that your program will not be able to handle. PDF dictionaries and lists can contain other objects. Regex can't handle recursive structures, at least not Python re module.
A pdf file is a tree of objects and streams:
Dictionaries: << (name value)* >>
Lists: [ (value)* ]
Names: / (regular char)*
Strings: ( (char)* )
Hex strings: < (hexchar)* >
Numbers: (-)? ((digit)+ | (digit)+ . (digit)* | . (digit)+)
Booleans: true | false
References: (digit)+ (whitespace)+ (digit)+ (whitespace)+ R
Whitespace and comments are ignored in most places.
Comments start with % and run until the end of the line.
Indirect objects are specified as:
1 0 obj
(any object)
endobj
This object can then be referenced as 1 0 R. Indirect dictionaries can also have a stream attached:
1 0 obj
<<
/Length 22
>>
stream
(22 bytes of raw data)
endstream
endobj
A PDF file looks something like this:
%PDF-1.4
%ÿÿÿÿ
1 0 obj
<< /Author (MizardX) >>
endobj
2 0 obj
<<
/Type /Catalog
% more required keys
>>
endobj
%lots of more indirect objects, one after another
trailer
<<
/Info 1 0 R
/Root 2 0 R
% ... more required keys
>>
xref
0 3
0000000000 65535 f
0000000015 00000 n
0000000054 00000 n
startxref
225
%%EOF
The root of the object tree is the trailer object. Every objects is referenced directly or indirectly from this dictionary.
There are a lot more complexity hidden inside the streams, but that does not affect the file structure.
The full specification can be found at Adobe's website.
A:
You need to use *?as the non-greedy version - see documentation here.
Also, note that PDF format is very complex - especially when it starts having binary streams within it - but if you know the PDFs you are looking at are simple then this should work.
A:
A question mark after the repeated part should take the minimal amount of characters. Also comma is not necessary because \S already takes it into account.
\d+\s\d+\sobj[\s\S]*?endobj
A:
Not exactly an answer to your exact question, but you might want to have look at existing pdf parsing libraries in python, for example: pdfminer or pyPdf. (even if you do not end up using them, you might as well have a look and see how they do it)
| Parsing PDF file using Regular expressions in Python | I am trying to parse some object elements from a PDF file using re module of Python. My goal is to parse each PDF object using a regular expression.
A PDF object example is the following:
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/Kids [ 3 0 R ]
/Count 1
>>
endobj
...
When I use "\d+\s\d+\sobj[\s,\S]*endobj" it doesn't work (it keeps parsing util last endobj is found). How can I modify regular expression in order to parse each object seperately (in other words the part from 1 0 obj until endobj)?
| [
"If you are using only regex, it is easy to construct a PDF file that your program will not be able to handle. PDF dictionaries and lists can contain other objects. Regex can't handle recursive structures, at least not Python re module.\nA pdf file is a tree of objects and streams:\n\nDictionaries: << (name value)*... | [
8,
2,
2,
2
] | [] | [] | [
"parsing",
"pdf",
"python",
"regex"
] | stackoverflow_0003915131_parsing_pdf_python_regex.txt |
Q:
Extending python Queue.PriorityQueue (worker priority, work package types)
I would like to extend the Queue.PriorityQueue described here: http://docs.python.org/library/queue.html#Queue.PriorityQueue
The queue will hold work packages with a priority. Workers will get work packages and process them. I want to make the following additions:
Workers have a priority too. When multiple workers are idle the one with the highest priority should process an incoming work package.
Not every worker can process every work package, so a mechanism is needed that checks if work package type and worker capabilities have a match.
I am looking for hints, how this is best implemented (starting from scratch, extending PrioriyQueue or Queue, ...).
edit
Here is my first (untested) try. The basic idea is that all waiting threads will be notified. Then they all try to get a work item through _choose_worker(self, worker). (Made it community wiki)
edit
Works for some simple tests now...
edit
Added a custom BaseManager and a local copy of the worker list in the _choose_worker function.
edit
bug fix
import Queue
from Queue import Empty, Full
from time import time as _time
import heapq
class AdvancedQueue(Queue.PriorityQueue):
# Initialize the queue representation
def _init(self, _maxsize):
self.queue = []
self.worker = []
def put(self, item, block=True, timeout=None):
'''
Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notifyAll() # only change
finally:
self.not_full.release()
def get(self, worker, block=True, timeout=None):
self.not_empty.acquire()
try:
self._put_worker(worker)
if not block:
if not self._qsize():
raise Empty
else:
return self._choose_worker(worker)
elif timeout is None:
while True:
while not self._qsize():
self.not_empty.wait()
try:
return self._choose_worker(worker)
except Empty:
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
def wait(endtime):
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
while True:
while not self._qsize():
wait(endtime)
try:
return self._choose_worker(worker)
except Empty:
wait(endtime)
finally:
self._remove_worker(worker)
self.not_empty.release()
# Put a new worker in the worker queue
def _put_worker(self, worker, heappush=heapq.heappush):
heappush(self.worker, worker)
# Remove a worker from the worker queue
def _remove_worker(self, worker):
self.worker.remove(worker)
# Choose a matching worker with highest priority
def _choose_worker(self, worker):
worker_copy = self.worker[:] # we need a copy so we can remove assigned worker
for item in self.queue:
for enqueued_worker in worker_copy:
if item[1].type in enqueued_worker[1].capabilities:
if enqueued_worker == worker:
self.queue.remove(item)
self.not_full.notify()
return item
else:
worker_copy.remove(enqueued_worker)
# item will be taken by enqueued_worker (which has higher priority),
# so enqueued_worker is busy and can be removed
continue
raise Empty
A:
I think you are describing a situation where you have two "priority queues" - one for the jobs and one for the workers. The naive approach is to take the top priority job and the top priority worker and try to pair them. But of course this fails when the worker is unable to execute the job.
To fix this I'd suggest first taking the top priority job and then iterating over all the workers in order of descending priority until you find one that can process that job. If none of the workers can process the job then take the second highest priority job, and so on. So effectively you have nested loops, something like this:
def getNextWorkerAndJobPair():
for job in sorted(jobs, key=priority, reverse=True):
for worker in sorted(workers, key=priority, reverse=True):
if worker.can_process(job):
return (worker, job)
The above example sorts the data unnecessarily many times though. To avoid this it would be best to store the data already in sorted order. As for what data structures to use, I'm not really sure what the best is. Ideally you would want O(log n) inserts and removals and to be able to iterate over the collection in sorted order in O(n) time. I think PriorityQueue meets the first of those requirements but not the second. I imagine that sortedlist from the blist package would work, but I haven't tried it myself and the webpage isn't specific about the performance guarantees that this class offers.
The way I have suggested to iterate over the jobs first and then over the workers in the inner loop is not the only approach you could take. You could also reverse the order of the loops so that you choose the highest priority worker first and then try to find a job for it. Or you could find the valid (job, worker) pair that has the maximum value of f(priority_job, priority_worker) for some function f (for example just add the priorities).
A:
The only answer was useful but not detailed enough, so I will accept my own answer for now. See the code in the question.
| Extending python Queue.PriorityQueue (worker priority, work package types) | I would like to extend the Queue.PriorityQueue described here: http://docs.python.org/library/queue.html#Queue.PriorityQueue
The queue will hold work packages with a priority. Workers will get work packages and process them. I want to make the following additions:
Workers have a priority too. When multiple workers are idle the one with the highest priority should process an incoming work package.
Not every worker can process every work package, so a mechanism is needed that checks if work package type and worker capabilities have a match.
I am looking for hints, how this is best implemented (starting from scratch, extending PrioriyQueue or Queue, ...).
edit
Here is my first (untested) try. The basic idea is that all waiting threads will be notified. Then they all try to get a work item through _choose_worker(self, worker). (Made it community wiki)
edit
Works for some simple tests now...
edit
Added a custom BaseManager and a local copy of the worker list in the _choose_worker function.
edit
bug fix
import Queue
from Queue import Empty, Full
from time import time as _time
import heapq
class AdvancedQueue(Queue.PriorityQueue):
# Initialize the queue representation
def _init(self, _maxsize):
self.queue = []
self.worker = []
def put(self, item, block=True, timeout=None):
'''
Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notifyAll() # only change
finally:
self.not_full.release()
def get(self, worker, block=True, timeout=None):
self.not_empty.acquire()
try:
self._put_worker(worker)
if not block:
if not self._qsize():
raise Empty
else:
return self._choose_worker(worker)
elif timeout is None:
while True:
while not self._qsize():
self.not_empty.wait()
try:
return self._choose_worker(worker)
except Empty:
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
def wait(endtime):
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
while True:
while not self._qsize():
wait(endtime)
try:
return self._choose_worker(worker)
except Empty:
wait(endtime)
finally:
self._remove_worker(worker)
self.not_empty.release()
# Put a new worker in the worker queue
def _put_worker(self, worker, heappush=heapq.heappush):
heappush(self.worker, worker)
# Remove a worker from the worker queue
def _remove_worker(self, worker):
self.worker.remove(worker)
# Choose a matching worker with highest priority
def _choose_worker(self, worker):
worker_copy = self.worker[:] # we need a copy so we can remove assigned worker
for item in self.queue:
for enqueued_worker in worker_copy:
if item[1].type in enqueued_worker[1].capabilities:
if enqueued_worker == worker:
self.queue.remove(item)
self.not_full.notify()
return item
else:
worker_copy.remove(enqueued_worker)
# item will be taken by enqueued_worker (which has higher priority),
# so enqueued_worker is busy and can be removed
continue
raise Empty
| [
"I think you are describing a situation where you have two \"priority queues\" - one for the jobs and one for the workers. The naive approach is to take the top priority job and the top priority worker and try to pair them. But of course this fails when the worker is unable to execute the job.\nTo fix this I'd sugg... | [
1,
0
] | [] | [] | [
"parallel_processing",
"python",
"queue"
] | stackoverflow_0003849157_parallel_processing_python_queue.txt |
Q:
What is location of django Built-in tags and filters?
What is location of django Built-in tags and filters? I cant find anywhere... I need it to format datetime so then i can send right formt in JSON by AJAX response.. Or maybe you can suggest me another way to do that...
What i want to do it's import function which determinate filter... and use it to format my datetime in JSON.
Look.. i have...
media_items = Media.objects.filter(blablabla=blablabla)
than i do
data = serializers.serialize('json', media_items, fields=('name','duration','on_air'))
How can I do so in data(what is JSON) i have right date format? What is the simplest way?
A:
What do you mean location? Do you mean where in Django's code does it live? If so, the default filters live in django.template.defaultfilters.
If you're wanting to do date formatting in a view, then use dateformat.
You can see an example of how to use dateformat in the code for the time filter, visible here.
| What is location of django Built-in tags and filters? | What is location of django Built-in tags and filters? I cant find anywhere... I need it to format datetime so then i can send right formt in JSON by AJAX response.. Or maybe you can suggest me another way to do that...
What i want to do it's import function which determinate filter... and use it to format my datetime in JSON.
Look.. i have...
media_items = Media.objects.filter(blablabla=blablabla)
than i do
data = serializers.serialize('json', media_items, fields=('name','duration','on_air'))
How can I do so in data(what is JSON) i have right date format? What is the simplest way?
| [
"What do you mean location? Do you mean where in Django's code does it live? If so, the default filters live in django.template.defaultfilters.\nIf you're wanting to do date formatting in a view, then use dateformat.\nYou can see an example of how to use dateformat in the code for the time filter, visible here.\n"
... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003916332_django_python.txt |
Q:
Scipy optimize.curve_fit sometimes won't converge
I'm trying to use numpy.optimize.curve_fit to estimate the frequency and phase of an on/off sequence.
This is the code I'm using:
from numpy import *
from scipy import optimize
row = array([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0,])
def fit_func(x, a, b, c, d):
return c * sin (a * x + b) + d
p0 = [(pi/10.0), 5.0, row.std(), row.mean()]
result = optimize.curve_fit(fit_func, arange(len(row)), row, p0)
print result
This works. But on some rows, even though they seem perfectly ok, it fails.
Example of failing row:
row = array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,])
The error is:
RuntimeError: Optimal parameters not found: Both actual and predicted relative reductions in the sum of squares are at most 0.000000 and the relative error between two consecutive iterates is at most 0.000000
Which tells me very little about what's happened.
A quick test shows that varying the parameters in p0 will cause that row to succeed... and others to fail. Why is that?
A:
I tried both rows of data that you provided and both worked for me just fine. I'm using Scipy 0.8.0rc3. What version are you using? Another thing that might help is to set c and d to fixed values since they really should be the same every time. I set c to 0.6311786 and d to .5. You could also use an fft with zero padding and quadratic fitting around the peak to find the frequency if you want another method. Really, any pitch estimation method is applicable since you are looking for the fundamental frequency.
| Scipy optimize.curve_fit sometimes won't converge | I'm trying to use numpy.optimize.curve_fit to estimate the frequency and phase of an on/off sequence.
This is the code I'm using:
from numpy import *
from scipy import optimize
row = array([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0,])
def fit_func(x, a, b, c, d):
return c * sin (a * x + b) + d
p0 = [(pi/10.0), 5.0, row.std(), row.mean()]
result = optimize.curve_fit(fit_func, arange(len(row)), row, p0)
print result
This works. But on some rows, even though they seem perfectly ok, it fails.
Example of failing row:
row = array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,])
The error is:
RuntimeError: Optimal parameters not found: Both actual and predicted relative reductions in the sum of squares are at most 0.000000 and the relative error between two consecutive iterates is at most 0.000000
Which tells me very little about what's happened.
A quick test shows that varying the parameters in p0 will cause that row to succeed... and others to fail. Why is that?
| [
"I tried both rows of data that you provided and both worked for me just fine. I'm using Scipy 0.8.0rc3. What version are you using? Another thing that might help is to set c and d to fixed values since they really should be the same every time. I set c to 0.6311786 and d to .5. You could also use an fft with zero ... | [
2
] | [] | [] | [
"curve_fitting",
"numerical_methods",
"numpy",
"python",
"scipy"
] | stackoverflow_0003915480_curve_fitting_numerical_methods_numpy_python_scipy.txt |
Q:
gtk minimum size
Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of a TreeView, but is it available for general widgets?
A:
For C/C++: gtk_widget_set_size_request()
Sets the minimum size of a widget; that is, the widget's size request will be width by height.
PyGTK: def set_size_request(width, height)
| gtk minimum size | Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of a TreeView, but is it available for general widgets?
| [
"For C/C++: gtk_widget_set_size_request()\n\nSets the minimum size of a widget; that is, the widget's size request will be width by height. \n\nPyGTK: def set_size_request(width, height)\n"
] | [
10
] | [] | [] | [
"c",
"c++",
"gtk",
"pygtk",
"python"
] | stackoverflow_0003916762_c_c++_gtk_pygtk_python.txt |
Q:
SMTP ERROR: (552, '5.6.0 Submission denied Sender does not match originator )
I've writted a Python script to send emails via a relay server. I've tested that the appropriate email address's etc are permissioned etc by sending an email using Telnet. My Python script also work when set up to send via my old relay server.
Therefore i am confused as to why i am getting the following error message:
(552, '5.6.0 Submission denied Sender does not match originator <myEmailAddress>)
I've looked at the SMTP error 552 and it is caused by the message size being exceeded, but i am only sending an email containing a few lines of html which is only a few kb in size so i'm assuming i can safely rule this issue out.
Any other ideas as to what could be the issue?
EDIT:
Here is the Python code which generates the error.
1 #!/usr/bin/env python
2 import sys
3 from sys import argv
4 import smtplib
5 import logging
6 import logging.handlers
7
8 LOG_FILENAME = 'sendMail.log'
9 inputMessage = argv[1]
10 sender = 'hi@sender.com'
11 receivers = 'hi@sender.com'
12 #Reads in the file as a single string
13 message = open(inputMessage, 'r').read()
14 log = logging.getLogger()
15
16 def initializelogging():
17 log.setLevel(logging.DEBUG)
18 fileformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
19 filehandler = logging.handlers.RotatingFileHandler(
20 LOG_FILENAME,
21 maxBytes=10000000,
22 backupCount=100)
23 filehandler.setFormatter(fileformatter)
24 consoleformatter = logging.Formatter('%(levelname)s: %(message)s')
25 consolehandler = logging.StreamHandler()
26 consolehandler.setLevel(logging.INFO)
27 consolehandler.setFormatter(consoleformatter)
28 log.addHandler(filehandler)
29 log.addHandler(consolehandler)
30 initializelogging()
31
32 def sendMail():
33 try:
34
35 smtpObj = smtplib.SMTP('mailserver@server.com')
36 smtpObj.sendmail(sender,sender, message)
37 print "Successfully sent email"
38 log.info('Successfully sent email')
39 except Exception, err:
40 log.error('Unable to send email. See below stack trace........')
41 log.error('%s\n' % str(err))
42 sendMail()
A:
I can't guarantee that either of these is the actual cause of the error, but:
I think the message you're getting might be saying that the From: header in your message doesn't match the e-mail address you are using for the sender in the sendmail() call. Make sure that the message you are reading from the file a) has valid SMTP headers (at least From, To, and Subject, and MIME-Version and Content-Type wouldn't hurt) and more specifically b) has a From: hi@sender.com header.
The instantiation for a SMTP object takes a server address, not an e-mail address. You should be using smtpObj = smtplib.SMTP('mail.server.com') or something else without so much @ in it. Otherwise, it may not be connecting to the server you think it is.
| SMTP ERROR: (552, '5.6.0 Submission denied Sender does not match originator ) | I've writted a Python script to send emails via a relay server. I've tested that the appropriate email address's etc are permissioned etc by sending an email using Telnet. My Python script also work when set up to send via my old relay server.
Therefore i am confused as to why i am getting the following error message:
(552, '5.6.0 Submission denied Sender does not match originator <myEmailAddress>)
I've looked at the SMTP error 552 and it is caused by the message size being exceeded, but i am only sending an email containing a few lines of html which is only a few kb in size so i'm assuming i can safely rule this issue out.
Any other ideas as to what could be the issue?
EDIT:
Here is the Python code which generates the error.
1 #!/usr/bin/env python
2 import sys
3 from sys import argv
4 import smtplib
5 import logging
6 import logging.handlers
7
8 LOG_FILENAME = 'sendMail.log'
9 inputMessage = argv[1]
10 sender = 'hi@sender.com'
11 receivers = 'hi@sender.com'
12 #Reads in the file as a single string
13 message = open(inputMessage, 'r').read()
14 log = logging.getLogger()
15
16 def initializelogging():
17 log.setLevel(logging.DEBUG)
18 fileformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
19 filehandler = logging.handlers.RotatingFileHandler(
20 LOG_FILENAME,
21 maxBytes=10000000,
22 backupCount=100)
23 filehandler.setFormatter(fileformatter)
24 consoleformatter = logging.Formatter('%(levelname)s: %(message)s')
25 consolehandler = logging.StreamHandler()
26 consolehandler.setLevel(logging.INFO)
27 consolehandler.setFormatter(consoleformatter)
28 log.addHandler(filehandler)
29 log.addHandler(consolehandler)
30 initializelogging()
31
32 def sendMail():
33 try:
34
35 smtpObj = smtplib.SMTP('mailserver@server.com')
36 smtpObj.sendmail(sender,sender, message)
37 print "Successfully sent email"
38 log.info('Successfully sent email')
39 except Exception, err:
40 log.error('Unable to send email. See below stack trace........')
41 log.error('%s\n' % str(err))
42 sendMail()
| [
"I can't guarantee that either of these is the actual cause of the error, but:\n\nI think the message you're getting might be saying that the From: header in your message doesn't match the e-mail address you are using for the sender in the sendmail() call. Make sure that the message you are reading from the file a)... | [
0
] | [] | [] | [
"email",
"html_email",
"python",
"smtp",
"smtplib"
] | stackoverflow_0003915151_email_html_email_python_smtp_smtplib.txt |
Q:
Implementing a text-based fallback for pygtk applications
I have a pygtk application and would like to provide a text-based fallback mode for it. When mporting gtk without a X display available I see only a GtkWarning on stderr but no exception I could take advantage of and checking for DISPLAY seems like an ugly hack. How can I implement this?
A:
Checking gtk.gdk.screen_get_default() does it, however there seems no way to suppress the GTK warnings.
| Implementing a text-based fallback for pygtk applications | I have a pygtk application and would like to provide a text-based fallback mode for it. When mporting gtk without a X display available I see only a GtkWarning on stderr but no exception I could take advantage of and checking for DISPLAY seems like an ugly hack. How can I implement this?
| [
"Checking gtk.gdk.screen_get_default() does it, however there seems no way to suppress the GTK warnings.\n"
] | [
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003914370_pygtk_python.txt |
Q:
Python Threading Concept Question
I'm currently in the process of writing a client server app as an exercise and I've gotten pretty much everything to work so far, but there is a mental hurdle that I haven't been able to successfully google myself over.
In the server application am I correct in my thinking that threading the packet handler and database handler to work from a stack is the right thing to do? The idea is that one thread loops listening for packets and adds the data to a stack and then the other thread pops the data off the bottom of the stack and does some checks against an SQL db.
In this particular case, it's more important for the packet handler to keep working. I guess my question is, is this an appropriate use of threads and where am I going to run into problems that require thread locking, for example, should I lock the db handler when the packet thread adds to the stack to avoid an issue with trying to write and read say, the only value in the stack, etc.
Thanks everyone!
Here is a snippet of the code, mind you it's in progress so don't judge, also my first attempt at python (which I am enjoying more than perl or php at the moment!).
class socketListen(threading.Thread):
def run(self):
while True:
datagram = s.recv('1024')
if not datagram:
break
packetArray = datagram.split(',')
if packetArray[0] = '31337':
listHandle.put(packetArray)
s.close()
class stackOperations(threading.Thread):
def run(self):
while True:
#pull the last item off the stack and run ops on it
#listHandle.getLast is the last item on the queue
def
class listHandle():
def put(shiftData):
if not mainStack:
mainStack = []
mainStack.insert(0,shiftData)
def getLast:
return mainStack.pop()
A:
This is what queues are for. Replace stack with queue and no, you won't have to use any other synchronization methods. Incidentally, multiprocessing is better than threading, since it can take advantage of multicore/hyperthreaded processors. The interfaces are pretty similar, so it's worth looking into switching.
| Python Threading Concept Question | I'm currently in the process of writing a client server app as an exercise and I've gotten pretty much everything to work so far, but there is a mental hurdle that I haven't been able to successfully google myself over.
In the server application am I correct in my thinking that threading the packet handler and database handler to work from a stack is the right thing to do? The idea is that one thread loops listening for packets and adds the data to a stack and then the other thread pops the data off the bottom of the stack and does some checks against an SQL db.
In this particular case, it's more important for the packet handler to keep working. I guess my question is, is this an appropriate use of threads and where am I going to run into problems that require thread locking, for example, should I lock the db handler when the packet thread adds to the stack to avoid an issue with trying to write and read say, the only value in the stack, etc.
Thanks everyone!
Here is a snippet of the code, mind you it's in progress so don't judge, also my first attempt at python (which I am enjoying more than perl or php at the moment!).
class socketListen(threading.Thread):
def run(self):
while True:
datagram = s.recv('1024')
if not datagram:
break
packetArray = datagram.split(',')
if packetArray[0] = '31337':
listHandle.put(packetArray)
s.close()
class stackOperations(threading.Thread):
def run(self):
while True:
#pull the last item off the stack and run ops on it
#listHandle.getLast is the last item on the queue
def
class listHandle():
def put(shiftData):
if not mainStack:
mainStack = []
mainStack.insert(0,shiftData)
def getLast:
return mainStack.pop()
| [
"This is what queues are for. Replace stack with queue and no, you won't have to use any other synchronization methods. Incidentally, multiprocessing is better than threading, since it can take advantage of multicore/hyperthreaded processors. The interfaces are pretty similar, so it's worth looking into switching.\... | [
4
] | [] | [] | [
"arrays",
"multithreading",
"python",
"thread_safety"
] | stackoverflow_0003917036_arrays_multithreading_python_thread_safety.txt |
Q:
Split up python packets?
Is there a way python can distinguish between packets being sent ? e.g.
python receives data
it process data
clients sends first packet
client sends second packet
python receives data, can i receive the first packet rather then all info in the buffer
I know i can set it up up so it sends data i confirm and the client wont send more data it i have confirmed that have a processed the last piece but i'd rather not
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("", 2000))
sock.listen(5)
all the relevant socket data
A:
There are basically two approaches:
At the start of each packet, send an integer specifying how long that packet will be. When you receive data, read the integer first, then read that many more bytes as the first packet.
Send some sort special marker between packets. This only works if you can guarantee that the marker cannot occur within a packet.
As S. Lott points out, you could instead use UDP (which is packet-based) instead of TCP (which is stream-based), but then you give up the other features that TCP provides (retransmission of dropped packets, sequential packets, and congestion control). It's not too hard to write your own code for retransmission, but congestion control is difficult to get right.
A:
Is there a way python can distinguish between packets being sent ?
Yes. Use UDP instead of TCP.
A:
Netstring is a simple serialization
format used to send data packets. Each
data packet is of the form
'length:data'.
http://en.wikipedia.org/wiki/Netstring
Python networking frameworks like
twisted has direct support for
netstring.
| Split up python packets? | Is there a way python can distinguish between packets being sent ? e.g.
python receives data
it process data
clients sends first packet
client sends second packet
python receives data, can i receive the first packet rather then all info in the buffer
I know i can set it up up so it sends data i confirm and the client wont send more data it i have confirmed that have a processed the last piece but i'd rather not
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("", 2000))
sock.listen(5)
all the relevant socket data
| [
"There are basically two approaches:\n\nAt the start of each packet, send an integer specifying how long that packet will be. When you receive data, read the integer first, then read that many more bytes as the first packet.\nSend some sort special marker between packets. This only works if you can guarantee that... | [
1,
0,
0
] | [] | [] | [
"packets",
"python",
"sockets"
] | stackoverflow_0003914542_packets_python_sockets.txt |
Q:
Python tarfile module overwrites existing files during extraction - how to disable it?
Is there a way prevent tarfile.extractall (API) from overwriting existing files? By "prevent" I mean ideally raising an exception when an overwrite is about to happen. The current behavior is to silently overwrite the files.
A:
You could check result of tarfile.getnames against the existing files and raise your error.
A:
Have you tried setting tarfile.errorlevel to 2? That will cause non-fatal errors to be raised. I'm assuming an overwrite falls in that category.
| Python tarfile module overwrites existing files during extraction - how to disable it? | Is there a way prevent tarfile.extractall (API) from overwriting existing files? By "prevent" I mean ideally raising an exception when an overwrite is about to happen. The current behavior is to silently overwrite the files.
| [
"You could check result of tarfile.getnames against the existing files and raise your error.\n",
"Have you tried setting tarfile.errorlevel to 2? That will cause non-fatal errors to be raised. I'm assuming an overwrite falls in that category.\n"
] | [
3,
0
] | [] | [] | [
"exception",
"python",
"tarfile"
] | stackoverflow_0003917491_exception_python_tarfile.txt |
Q:
Twisted client for a send only protocol that is tolerant of disconnects
I've decided to dip my toe into the world of asynchronous python with the help of twisted. I've implemented some of the examples from the documentation, but I'm having a difficult time finding an example of the, very simple, client I'm trying to write.
In short I'd like a client which establishes a tcp connection with a server and then sends simple "\n" terminated string messages off of a queue object to the server. The server doesn't ever respond with any messages so my client is fully unidirectional. I /think/ that what I want is some combination of this example and the twisted.internet.protocols.basic.LineReceiver convenience protocol. This feels like it should be just about the simplest thing one could do in twisted, but none of the documentation or examples I've seen online seem to fit quite right.
A:
What I have done is not used a Queue but I am illustrating the code that sends a line, once a connection is made. There are bunch of print stuff that will help you understand on what is going on.
Usual import stuff:
from twisted.web import proxy
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.protocols import basic
from twisted.python import log
import sys
log.startLogging(sys.stdout)
You create a protocol derived from line receiver, set the delimiter.
In this case, I simply write a string "www" once the connection is made.
The key thing is to look at protocol interface at twisted.internet.interface.py and understand the various methods of protocol and what they do and when they are called.
class MyProtocol(basic.LineReceiver):
#def makeConnection(self, transport):
# print transport
def connectionLost(self, reason):
print reason
self.sendData = False
def connectionMade(self):
print "connection made"
self.delimiter = "\n"
self.sendData = True
print self.transport
self.sendFromQueue()
def sendFromQueue(self):
while self.sendData:
msg = dataQueue.get()
self.sendLine(msg)
# you need to handle empty queue
# Have another function to resume
Finally, A protocol factory that will create a protocol instance for every connection.
Look at method : buildProtcol.
class myProtocolFactory():
protocol = MyProtocol
def doStart(self):
pass
def startedConnecting(self, connectorInstance):
print connectorInstance
def buildProtocol(self, address):
print address
return self.protocol()
def clientConnectionLost(self, connection, reason):
print reason
print connection
def clientConnectionFailed(self, connection, reason):
print connection
print reason
def doStop(self):
pass
Now you use a connector to make a connection:
reactor.connectTCP('localhost', 50000, myProtocolFactory())
reactor.run()
I ran this and connected it to an server that simply prints what it receives and hence send no ack back. Here is the output:
1286906080.08 82 INFO 140735087148064 __main__ conn_made: client_address=127.0.0.1:50277
1286906080.08 83 DEBUG 140735087148064 __main__ created handler; waiting for loop
1286906080.08 83 DEBUG 140735087148064 __main__ handle_read
1286906080.08 83 DEBUG 140735087148064 __main__ after recv
'www\n'
Recieved: 4
The above example if not fault tolerant. To reconnect , when a connection is lost, you can derive your protocol factory from an existing twisted class - ReconnectingClientFactory.
Twisted has almost all the tools that you would need :)
class myProtocolFactory(ReconnectingClientFactory):
protocol = MyProtocol
def buildProtocol(self, address):
print address
return self.protocol()
For further reference
I suggest that you read : http://krondo.com/?page_id=1327
[Edited: As per comment below]
| Twisted client for a send only protocol that is tolerant of disconnects | I've decided to dip my toe into the world of asynchronous python with the help of twisted. I've implemented some of the examples from the documentation, but I'm having a difficult time finding an example of the, very simple, client I'm trying to write.
In short I'd like a client which establishes a tcp connection with a server and then sends simple "\n" terminated string messages off of a queue object to the server. The server doesn't ever respond with any messages so my client is fully unidirectional. I /think/ that what I want is some combination of this example and the twisted.internet.protocols.basic.LineReceiver convenience protocol. This feels like it should be just about the simplest thing one could do in twisted, but none of the documentation or examples I've seen online seem to fit quite right.
| [
"What I have done is not used a Queue but I am illustrating the code that sends a line, once a connection is made. There are bunch of print stuff that will help you understand on what is going on.\nUsual import stuff:\nfrom twisted.web import proxy\nfrom twisted.internet import reactor\nfrom twisted.internet import... | [
1
] | [] | [] | [
"asynchronous",
"client",
"networking",
"python",
"twisted"
] | stackoverflow_0003917382_asynchronous_client_networking_python_twisted.txt |
Q:
Post Binary Sting to Django app using HTML 5
I read in a file via HTML5 FileReader and jQuery like so:
holder.ondrop = function(e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onloadend = function(event) {
$.ajax({
url:"/path/to/upload",
type: "POST",
data: event.target.result,
success: function(data, status, xhr) {
alert("success!");
},
error: function(xhr, status, error) {
alert("fail")
},
});
};
reader.readAsBinaryString(file);
return false;
};
The "ondrop" is used to handle drag and drop on an element i've named "holder".
The file is submitted to my django app, and if I simply
print request.raw_post_data
I see binary output in my console.
I try to write this to a file like so (yes in my test it's always a jpg):
f = open('/tmp/file.jpg', 'wb')
f.write(request.raw_post_data)
f.close()
And the file is written but when I try to open it, it seems corrupted.
My suspicion is that it has something to do with request.raw_post_data getting incorrectly encoded but i'm not exactly sure how to correct it ... raw_post_data looks like binary although type() returns str.
Any thoughts?
A:
this post was really helpful for me, maybe it will be helpful for you too
http://hacks.mozilla.org/2010/06/html5-adoption-stories-box-net-and-html5-drag-and-drop/
I ended up changing my javascript to be:
holder.ondrop = function(e) {
e.preventDefault();
var file = e.dataTransfer.files[0];
var request = new XMLHttpRequest();
request.open("POST", upload_url, true); // open asynchronous post request
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.send(file);
};
and voila.
| Post Binary Sting to Django app using HTML 5 | I read in a file via HTML5 FileReader and jQuery like so:
holder.ondrop = function(e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onloadend = function(event) {
$.ajax({
url:"/path/to/upload",
type: "POST",
data: event.target.result,
success: function(data, status, xhr) {
alert("success!");
},
error: function(xhr, status, error) {
alert("fail")
},
});
};
reader.readAsBinaryString(file);
return false;
};
The "ondrop" is used to handle drag and drop on an element i've named "holder".
The file is submitted to my django app, and if I simply
print request.raw_post_data
I see binary output in my console.
I try to write this to a file like so (yes in my test it's always a jpg):
f = open('/tmp/file.jpg', 'wb')
f.write(request.raw_post_data)
f.close()
And the file is written but when I try to open it, it seems corrupted.
My suspicion is that it has something to do with request.raw_post_data getting incorrectly encoded but i'm not exactly sure how to correct it ... raw_post_data looks like binary although type() returns str.
Any thoughts?
| [
"this post was really helpful for me, maybe it will be helpful for you too\nhttp://hacks.mozilla.org/2010/06/html5-adoption-stories-box-net-and-html5-drag-and-drop/\nI ended up changing my javascript to be:\nholder.ondrop = function(e) {\n e.preventDefault();\n\n var file = e.dataTransfer.files[0];\n ... | [
2
] | [] | [] | [
"django",
"file_upload",
"html",
"jquery",
"python"
] | stackoverflow_0003916989_django_file_upload_html_jquery_python.txt |
Q:
Get parameters of object in metaclass of this object
My problem is a python/django mix. I have a form model that will display some fields. Basing on some parameter of this model, the data sent to metaclass creating this object should differ. But how can I reach this parameter when inside the body of Meta ? Should I use some global var instead of object parameter (as it is introduced only to store value temporarily) ?
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
instance = kwargs.get("instance")
self.type = None
try:
type = self.instance.template_id
except:
pass
class Meta:
model = ContentBase
fields = ["title", "slug", "description", "text", "price",]
#here I need to have the value of 'type'
if type != 2:
try:
fields.remove("price")
except:
pass
A:
You can't do anything dynamic within Meta. That's not what it's for.
Why can't you do it all within __init__? You can modify self.fields from there.
A:
Just as Daniel proposed, I moved the whole thing to __init__ :
type = None
try:
type = self.instance.template_id
except:
pass
if type != 2:
self.fields.pop("price")
else:
| Get parameters of object in metaclass of this object | My problem is a python/django mix. I have a form model that will display some fields. Basing on some parameter of this model, the data sent to metaclass creating this object should differ. But how can I reach this parameter when inside the body of Meta ? Should I use some global var instead of object parameter (as it is introduced only to store value temporarily) ?
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
instance = kwargs.get("instance")
self.type = None
try:
type = self.instance.template_id
except:
pass
class Meta:
model = ContentBase
fields = ["title", "slug", "description", "text", "price",]
#here I need to have the value of 'type'
if type != 2:
try:
fields.remove("price")
except:
pass
| [
"You can't do anything dynamic within Meta. That's not what it's for.\nWhy can't you do it all within __init__? You can modify self.fields from there.\n",
"Just as Daniel proposed, I moved the whole thing to __init__ :\n type = None\n try:\n type = self.instance.template_id\n except:\n pass... | [
2,
1
] | [] | [] | [
"django",
"metaclass",
"python",
"scope"
] | stackoverflow_0003916570_django_metaclass_python_scope.txt |
Q:
Iron Python vs Razor
I have a little bit of experience with the new Razor syntax, but none with Iron Python. I was wondering do both meet the same needs? Is one favored by Microsoft over the other (or will be)? Appreciate your thoughts, as I'm toying with the idea of learning Iron Python, but if Razor can meet the same need, I probably won't.
A:
To expand on the answer given by PaulStack:
Razor is a templating engine (with a slant towards templating XML-style documents, e.g. HTML web pages) that is available as a View Engine in MVC 3 as well as the default page syntax in ASP.NET Web Pages (which is part of the WebMatrix stack). The Razor parser uses assumptions about the structure of XML documents as well as constructs available in the two supported programming languages (C# and Visual Basic) to minimize the number of transition characters that are required to go between code mode and markup mode.
While it has been written with a focus on emitting HTML, it has been generalized to support arbitrary text templating tasks (though in some cases you might need to use special transition tokens to force switches between code and text).
On the other hand, IronPython is a programming language. It is not a templating engine, though naturally it can be used to write code that emits a stream of text.
If you are already comfortable with C# (or VB) then I would suggest you try Razor. It's a fairly simple extension of the language syntax and allows for very smooth transitions between markup and code.
A:
Razor is a view engine for ASP.NET MVC 3 - so i believe it has nothing to do with the space that IronPython occupies
if im wrong then i have certainly missed something
A:
I was at a talk by one of the guys working on IronPython and IronRuby. The general sentiment he seemed to express is that IronPython is not as up to the task of building modern ASP.NET MVC sites as IronRuby or C# are. That said, this could have changed since then.
But you're comparing apples to oranges here. IronPython is a full-fledged dynamic language. Razor is just a markup language and view engine for defining views in an ASP.NET MVC site. The controllers and most of the code for the application must still be written in an actual language (such as C#, Python, or the like).
| Iron Python vs Razor | I have a little bit of experience with the new Razor syntax, but none with Iron Python. I was wondering do both meet the same needs? Is one favored by Microsoft over the other (or will be)? Appreciate your thoughts, as I'm toying with the idea of learning Iron Python, but if Razor can meet the same need, I probably won't.
| [
"To expand on the answer given by PaulStack:\nRazor is a templating engine (with a slant towards templating XML-style documents, e.g. HTML web pages) that is available as a View Engine in MVC 3 as well as the default page syntax in ASP.NET Web Pages (which is part of the WebMatrix stack). The Razor parser uses assu... | [
7,
5,
1
] | [] | [] | [
"ironpython",
"python",
"razor"
] | stackoverflow_0003916787_ironpython_python_razor.txt |
Q:
Python Threads (or their equivalent) on Google Application Engine Workaround?
I want to make a Google App Engine app that does the following:
Client makes an asynchronous http request
Server starts processing that request
Client makes ajax http requests to get progress
The problem is that the server processing (step #2) may take more than 30 seconds.
I know that you can't have threads on Google Application Engine and that all tasks must complete within 30 seconds or they get shut down. Is there some way to work around this?
Also, I'm using python-django as a backend.
A:
You'll want to use the Task Queue API, probably via deferred tasks. The deferred API makes working with Task Queues dramatically simpler.
Essentially, you'll want to spawn a task to start the processing. That task should catch DeadlineExceeded exceptions and reschedule itself (again via the deferred API) to continue processing. This requires that your tasks be able to keep track of their own progress. They can also update their own status in memcache, which you can use to write a view that checks a task's status. That view can then be polled via Ajax.
| Python Threads (or their equivalent) on Google Application Engine Workaround? | I want to make a Google App Engine app that does the following:
Client makes an asynchronous http request
Server starts processing that request
Client makes ajax http requests to get progress
The problem is that the server processing (step #2) may take more than 30 seconds.
I know that you can't have threads on Google Application Engine and that all tasks must complete within 30 seconds or they get shut down. Is there some way to work around this?
Also, I'm using python-django as a backend.
| [
"You'll want to use the Task Queue API, probably via deferred tasks. The deferred API makes working with Task Queues dramatically simpler.\nEssentially, you'll want to spawn a task to start the processing. That task should catch DeadlineExceeded exceptions and reschedule itself (again via the deferred API) to con... | [
4
] | [] | [] | [
"django",
"google_app_engine",
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0003917432_django_google_app_engine_multithreading_python_python_multithreading.txt |
Q:
Why is 3<<1 == 6 in python?
Possible Duplicate:
Absolute Beginner's Guide to Bit Shifting?
anyone can explain me that operator << or >>
A:
The << and >> operators are bitshift operators. x << 1 shifts all the bits in x up to the next most significant bit, effectively multiplying by 2. More generally, x << n shifts the bits up n positions. To understand how this operation works it is easiest to look at the binary representation:
3 0000011 = 3
3 << 1 0000110 = 6
3 << 2 0001100 = 12
3 << 3 0011000 = 24
Similarly the >> operator shifts the bits down:
58 0111010 = 58
58 >> 1 0011101 = 29
58 >> 2 0001110 = 14
58 >> 3 0000111 = 7
58 >> 4 0000011 = 3
58 >> 5 0000001 = 1
58 >> 6 0000000 = 0
A:
3, in binary, is 11 and shifted to left one bit is 110, or 6 in decimal.
Think of a << b as a * (2 ** b)
>> is for right-shifting. Think of a >> b as a // (2 ** b)
A:
It's a shift operator.
http://docs.python.org/reference/expressions.html#shifting-operations
A:
It's a bit shift, using a shifting operation.
Say you have a number, and looking at the lowest bits, you have 3:
0 0 1 1
If you shift it, you'll get 6, or:
0 1 1 0
| Why is 3<<1 == 6 in python? |
Possible Duplicate:
Absolute Beginner's Guide to Bit Shifting?
anyone can explain me that operator << or >>
| [
"The << and >> operators are bitshift operators. x << 1 shifts all the bits in x up to the next most significant bit, effectively multiplying by 2. More generally, x << n shifts the bits up n positions. To understand how this operation works it is easiest to look at the binary representation:\n3 0000011 = ... | [
34,
15,
4,
4
] | [] | [] | [
"bit_manipulation",
"operators",
"python"
] | stackoverflow_0003917948_bit_manipulation_operators_python.txt |
Q:
python statistical analysis
Given 15 players - 2 Goalkeepers, 5 defenders, 5 midfielders and 3 strikers, and the fact that each has a value and a score, I want to calculate the highest scoring team for the money I have. Each team must consist of 1 GK then a formation e.g. 4:4:2, 4:3:3 etc. I started with sample data such as this
player role points cost
I then did the following to evaluate all combinations
read each line into a list (for each role) then use itertools in a nested run to get all combinations
if line[1] == "G": G.append(line[0])
if line[1] == "D": D.append(line[0])
if line[1] == "M": M.append(line[0])
if line[1] == "S": S.append(line[0])
for gk in itertools.combinations(G,1):
for de in itertools.combinations(D,4):
for mi in itertools.combinations(M,4):
for st in itertools.combinations(S,2):
teams[str(count)]= " ".join(gk)+" "+" ".join(de)+" "+" ".join(mi)+" "+" ".join(st)
count +=1
Having got the teams, I calculate their points value, and the team cost. If it's lower than the threshold, I print it.
But if I now make this 20 goalkeepers, 150 defenders, 150 midfielders and 100 strikers, I understandably get out of memory.
What could I do to perform this analysis? Is it a generator rather than a recursive function that I need?
Many thanks
A:
You might be able to solve this problem with recursion. The following shows the basic outline, but ignores details like a team being composed of a certain number of certain types of players.
players=[{'name':'A','score':5,'cost':10},
{'name':'B','score':10,'cost':3},
{'name':'C','score':6,'cost':8}]
def player_cost(player):
return player['cost']
def player_score(player):
return player['score']
def total_score(players):
return sum(player['score'] for player in players)
def finance_team_recurse(budget, available_players):
affordable_players=[]
for player in available_players:
if player_cost(player)<=budget:
# Since we've ordered available players, the first player appended
# will be the one with the highest score.
affordable_players.append(player)
result=[]
if affordable_players:
candidate_player=affordable_players[0]
other_players=affordable_players[1:]
# if you include candidate_player on your team
team_with_candidate=finance_team_recurse(budget-player_cost(candidate_player),
other_players)
team_with_candidate.append(candidate_player)
score_of_team_with_candidate=total_score(team_with_candidate)
if score_of_team_with_candidate>total_score(other_players):
result=team_with_candidate
else:
# if you exclude candidate_player from your team
team_without_candidate=finance_team_recurse(budget, other_players)
score_of_team_without_candidate=total_score(team_without_candidate)
if score_of_team_with_candidate>score_of_team_without_candidate:
result=team_with_candidate
else:
result=team_without_candidate
return result
def finance_team(budget, available_players):
tmp=available_players[:]
# Sort so player with highest score is first. (Greedy algorithm?)
tmp.sort(key=player_score, reverse=True)
return finance_team_recurse(budget,tmp)
print(finance_team(20,players))
# [{'score': 6, 'cost': 8, 'name': 'C'}, {'score': 10, 'cost': 3, 'name': 'B'}]
20 choose 1 = 20 combinations
150 choose 4 = 20260275 combinations
100 choose 2 = 4950 combinations
So there are a total of 20*20260275*20260275*4950 = 40637395564486875000L
items in the teams dict. That takes a lot of memory.
for gk in itertools.combinations(G,1):
for de in itertools.combinations(D,4):
for mi in itertools.combinations(M,4):
for st in itertools.combinations(S,2):
#Don't collect the results into a dict.
#That's what's killing you (memory-wise).
#Just compute the cost and
#Just print the result here.
PS. 40637395564486875000L is on the order of 10**19. Assuming your program can process 10**6 combinations per second, it will take about 1.3 millions years for the program to complete...
A:
Functions and generators help a lot:
def make_teams(G, D, M, S):
""" returns all possible teams """
for gk in itertools.combinations(G,1):
for de in itertools.combinations(D,4):
for mi in itertools.combinations(M,4):
for st in itertools.combinations(S,2):
yield gk, de, mi, st
def get_cost( team ):
return sum( member.cost for member in team )
def good_teams( min_score=0):
for team in make_teams(G, D, M, S):
if get_cost( team ) > min_score:
yield team
for team in good_teams(min_score=100):
print team
It still generates all possible combinations, so you'll probably run out of time now, instead of memory.
What you're doing seems like a variation of the knapsack problem - you can do better than try all possible combination, but not much better.
One way to get a good solution fast is to sort the players by their score per money. You should get the top scoring teams first, but there are no guarantees that you get the best possible solution. Wikipedia calls this the "Greedy approximation algorithm".
def score_per_cost( player ):
return player.score / player.cost
def sorted_combinations(seq, n):
return itertools.combinations(
sorted(seq, key=score_per_cost, reverse=True),n)
def make_teams(G, D, M, S):
""" returns all possible teams """
for gk in sorted_combinations(G,1):
for de in sorted_combinations(D,4):
for mi in sorted_combinations(M,4):
for st in sorted_combinations(S,2):
yield gk, de, mi, st
def get_cost( team ):
return sum( member.cost for member in team )
def top_teams(n):
return itertools.islice(make_teams(G, D, M, S),n)
for team in top_teams(100):
print team
I'll leave adding the "cost per team < threshold" requirement to the reader (hint: it's one line in make_teams :p).
| python statistical analysis | Given 15 players - 2 Goalkeepers, 5 defenders, 5 midfielders and 3 strikers, and the fact that each has a value and a score, I want to calculate the highest scoring team for the money I have. Each team must consist of 1 GK then a formation e.g. 4:4:2, 4:3:3 etc. I started with sample data such as this
player role points cost
I then did the following to evaluate all combinations
read each line into a list (for each role) then use itertools in a nested run to get all combinations
if line[1] == "G": G.append(line[0])
if line[1] == "D": D.append(line[0])
if line[1] == "M": M.append(line[0])
if line[1] == "S": S.append(line[0])
for gk in itertools.combinations(G,1):
for de in itertools.combinations(D,4):
for mi in itertools.combinations(M,4):
for st in itertools.combinations(S,2):
teams[str(count)]= " ".join(gk)+" "+" ".join(de)+" "+" ".join(mi)+" "+" ".join(st)
count +=1
Having got the teams, I calculate their points value, and the team cost. If it's lower than the threshold, I print it.
But if I now make this 20 goalkeepers, 150 defenders, 150 midfielders and 100 strikers, I understandably get out of memory.
What could I do to perform this analysis? Is it a generator rather than a recursive function that I need?
Many thanks
| [
"You might be able to solve this problem with recursion. The following shows the basic outline, but ignores details like a team being composed of a certain number of certain types of players. \nplayers=[{'name':'A','score':5,'cost':10},\n {'name':'B','score':10,'cost':3},\n {'name':'C','score':6,'co... | [
5,
0
] | [] | [] | [
"python",
"statistics"
] | stackoverflow_0003917967_python_statistics.txt |
Q:
Problem with running a program on Pydev in Eclipse
I need your help,
I'm using Eclipse and Pydev plugin as python IDE.
I have configured and set environment variables, libraries etc etc
I created a project, and a module.
When I write these lines and run the program, it gives an error:
`a = 3
b = 4.6
print "%d is the value of a, %.2f is the value of b" %(a, b)`
and the error message is:
SyntaxError: Non-ASCII character '\xfd' in file C:\Users\dell\workspace\Deneme\src\test1\o3.py on line 9, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
However, when i write the same lines in IDLE, it runs without errors.
What is wrong with Pydev??
A:
Well, the error message pretty much sums it up: There is a non-ascii character in your file. Python 2 source files are expected to be ASCII only, or contain an # -*- coding: <encoding name> -*- (there are other valid forms, see the PEP the error refers to) comment at the top. For Python 3, UTF-8 is allowed too.
I'm pretty sure if you manually navigate to the project folder and run the file, you'll get the same error.
| Problem with running a program on Pydev in Eclipse | I need your help,
I'm using Eclipse and Pydev plugin as python IDE.
I have configured and set environment variables, libraries etc etc
I created a project, and a module.
When I write these lines and run the program, it gives an error:
`a = 3
b = 4.6
print "%d is the value of a, %.2f is the value of b" %(a, b)`
and the error message is:
SyntaxError: Non-ASCII character '\xfd' in file C:\Users\dell\workspace\Deneme\src\test1\o3.py on line 9, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
However, when i write the same lines in IDLE, it runs without errors.
What is wrong with Pydev??
| [
"Well, the error message pretty much sums it up: There is a non-ascii character in your file. Python 2 source files are expected to be ASCII only, or contain an # -*- coding: <encoding name> -*- (there are other valid forms, see the PEP the error refers to) comment at the top. For Python 3, UTF-8 is allowed too.\nI... | [
0
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0003918241_eclipse_pydev_python.txt |
Q:
Generic metaclass to keep track of subclasses?
I'm trying to write a generic metaclass to track subclasses
Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like:
def make_subtracker(root):
class SubclassTracker(type):
def __init__(cls, name, bases, dct):
print('registering %s' % (name,))
root._registry.append(cls)
super(SubclassTracker, cls).__init__(name, bases, dct)
return SubclassTracker
This way I could invoke it to generate a metaclass for a specific root class with:
__metaclass__ = make_subtracker(Root)
Here is where I bump into a problem. I cannot do this:
class Root(object):
_registry = []
__metaclass__ = make_subtracker(Root)
...because Root is not defined yet when I use make_subtracker(Root). I tried adding the __metaclass__ attribute later, so that at least it can be applied in subclasses:
class Root(object):
_registry = []
Root.__metaclass__ = make_subtracker(Root)
...but this doesn't work. __metaclass__ has a special processing when the class definition is read, as defined in Customizing class creation.
I'm looking for suggestions in order to do this (either change a class' metaclass at runtime in a way that it is applied to its subclasses, or any other alternative).
A:
I think you want something like this (untested):
class SubclassTracker(type):
def __init__(cls, name, bases, dct):
if not hasattr(cls, '_registry'):
cls._registry = []
print('registering %s' % (name,))
cls._registry.append(cls)
super(SubclassTracker, cls).__init__(name, bases, dct)
Then, for Python 2, you can invoke it like:
class Root(object):
__metaclass__ = SubclassTracker
for Python 3
class Root(object, metaclass=SubclassTracker):
Note that you don't need to stick the _registry attribute on there because stuff like that is what metaclasses are for. Since you already happen to have one laying around... ;)
Note also that you might want to move the registration code into an else clause so that the class doesn't register itself as a subclass.
A:
Python does this automatically for new-style classes, as mentioned in this answer to the similar queston How to find all the subclasses of a class given its name? here.
A:
Here's something I've been playing around with (that works):
def sublass_registry():
''' Create a metaclass to register subclasses '''
class SublassRegistryMeta(type):
def __init__(cls, name, bases, classdict):
if classdict.get('__metaclass__') is SublassRegistryMeta:
SublassRegistryMeta.lineage = [cls] # put root class at head of a list
else:
# sublclasses won't have __metaclass__ explicitly set to this class
# we know they're subclassees because this ctor is being called for them
SublassRegistryMeta.lineage.append(cls) # add subclass to list
type.__init__(cls, name, bases, classdict)
return SublassRegistryMeta
def subclasses(cls):
''' Return a list containing base and subclasses '''
try:
if cls.__metaclass__.lineage[0] is cls: # only valid for a root class
return cls.__metaclass__.lineage
except AttributeError:
pass
return None
class Car(object): # root class
__metaclass__ = sublass_registry()
class Audi(Car): # inherits __metaclass__
pass
class Ford(Car): # inherits __metaclass__
pass
class Audi2(Audi): # sub-subclass also inherits __metaclass__
pass
print subclasses(Car)
# [<class '__main__.Car'>, <class '__main__.Audi'>, <class '__main__.Ford'>, <class '__main__.Audi2'>]
print subclasses(Audi)
# None
| Generic metaclass to keep track of subclasses? | I'm trying to write a generic metaclass to track subclasses
Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like:
def make_subtracker(root):
class SubclassTracker(type):
def __init__(cls, name, bases, dct):
print('registering %s' % (name,))
root._registry.append(cls)
super(SubclassTracker, cls).__init__(name, bases, dct)
return SubclassTracker
This way I could invoke it to generate a metaclass for a specific root class with:
__metaclass__ = make_subtracker(Root)
Here is where I bump into a problem. I cannot do this:
class Root(object):
_registry = []
__metaclass__ = make_subtracker(Root)
...because Root is not defined yet when I use make_subtracker(Root). I tried adding the __metaclass__ attribute later, so that at least it can be applied in subclasses:
class Root(object):
_registry = []
Root.__metaclass__ = make_subtracker(Root)
...but this doesn't work. __metaclass__ has a special processing when the class definition is read, as defined in Customizing class creation.
I'm looking for suggestions in order to do this (either change a class' metaclass at runtime in a way that it is applied to its subclasses, or any other alternative).
| [
"I think you want something like this (untested):\nclass SubclassTracker(type):\n def __init__(cls, name, bases, dct):\n if not hasattr(cls, '_registry'):\n cls._registry = []\n print('registering %s' % (name,))\n cls._registry.append(cls)\n super(SubclassTracker, cls).__in... | [
11,
11,
2
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0003915315_metaclass_python.txt |
Q:
Having issues with flock() function
I have a question about how flock() works, particularly in python. I have a module that opens a serial connection (via os.open()). I need to make this thread safe. It's easy enough making it thread safe when working in the same module using threading.Lock(), but if the module gets imported from different places, it breaks.
I was thinking of using flock(), but I'm having trouble finding enough information about how exactly flock works. I read that flock() unlocks the file once the file is closed. But is there a situation that will keep the file open if python crashes?
And what exactly is allowed to use the locked file if LOCK_EX is set? Just the module that locked the file? Any module that was imported from the script that was originally run?
A:
When a process dies the OS should clean up any open file resources (with some caveats, I'm sure). This is because the advisory lock is released when the file is closed, an operation which occurs as part of the OS cleanup when the python process exits.
Remember, flock(2) is merely advisory:
Advisory locks allow cooperating processes to perform consistent operations on files, but [other, poorly behaved] processes may still access those files without using advisory locks.
flock(2) implements a readers-writer lock. You can't flock the same file twice with LOCK_EX, but any number of people can flock it with LOCK_SH simultaneously (as long as nobody else has a LOCK_EX on it).
The locking mechanism allows two types of locks: shared locks and exclusive locks. At any time multiple shared locks may be applied to a file, but at no time are multiple exclusive, or both shared and exclusive, locks allowed simultaneously on a file.
flock works at the OS/process level and is independent of python modules. One module may request n locks, or n locks could be requested across m modules. However, only one process can hold a LOCK_EX lock on a given file at a given time.
YMMV on a "non-UNIX" system or a non-local filesystem.
| Having issues with flock() function | I have a question about how flock() works, particularly in python. I have a module that opens a serial connection (via os.open()). I need to make this thread safe. It's easy enough making it thread safe when working in the same module using threading.Lock(), but if the module gets imported from different places, it breaks.
I was thinking of using flock(), but I'm having trouble finding enough information about how exactly flock works. I read that flock() unlocks the file once the file is closed. But is there a situation that will keep the file open if python crashes?
And what exactly is allowed to use the locked file if LOCK_EX is set? Just the module that locked the file? Any module that was imported from the script that was originally run?
| [
"When a process dies the OS should clean up any open file resources (with some caveats, I'm sure). This is because the advisory lock is released when the file is closed, an operation which occurs as part of the OS cleanup when the python process exits.\nRemember, flock(2) is merely advisory: \n\nAdvisory locks allo... | [
2
] | [] | [] | [
"fcntl",
"flock",
"locking",
"python"
] | stackoverflow_0003918385_fcntl_flock_locking_python.txt |
Q:
How to make cStringIO transparent to another function that expects a real local file
I came up with the following problem: CODE A works right now.. I am saving a png file called chart.png locally, and then I am loading it into the proprietary function (which I do not have access).
However, in CODE B, am trying to use cStringIO.StringIO() so that I do not have to write the file "chart.png" to the disk. But I cannot find a way to pass it to the pproprietaryfunction because it is expecting a real filename like "chart.png" (it looks like it even uses the split function to identify the extension).
CODE A (code running right now):
file = "chart.png"
pylab.savefig(file, format='png')
a = proprietaryfunction.add(file)
CODE B (what I am trying to do - and does not work):
file = cStringIO.StringIO()
pylab.savefig(file, format='png')
a = proprietaryfunction.add(file)
How can I make the use of cStringIO.StringIO() transparent to the proprietary function? Is there anyway that I can emulate a virtual file system in memory for this?
A:
Probably not, but there's always tempfile if you need a "clean" workaround...
| How to make cStringIO transparent to another function that expects a real local file | I came up with the following problem: CODE A works right now.. I am saving a png file called chart.png locally, and then I am loading it into the proprietary function (which I do not have access).
However, in CODE B, am trying to use cStringIO.StringIO() so that I do not have to write the file "chart.png" to the disk. But I cannot find a way to pass it to the pproprietaryfunction because it is expecting a real filename like "chart.png" (it looks like it even uses the split function to identify the extension).
CODE A (code running right now):
file = "chart.png"
pylab.savefig(file, format='png')
a = proprietaryfunction.add(file)
CODE B (what I am trying to do - and does not work):
file = cStringIO.StringIO()
pylab.savefig(file, format='png')
a = proprietaryfunction.add(file)
How can I make the use of cStringIO.StringIO() transparent to the proprietary function? Is there anyway that I can emulate a virtual file system in memory for this?
| [
"Probably not, but there's always tempfile if you need a \"clean\" workaround...\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python",
"stringio"
] | stackoverflow_0003917902_matplotlib_python_stringio.txt |
Q:
DNS resolver libraries with support for DNSSEC and/or experimental new RR types
What's the state of the art in DNS resolver libraries? I am particularly interested in full (not stub) resolvers that support any or all of: making multiple queries in one request packet, complete DNSSEC validation, returning detailed information about DNSSEC validation to the application, and can handle experimental new RRs without much hacking. Async queries are nice but not required.
Preferred implementation languages would be C, C++, Python, or Javascript, but I'll look at anything (I'd really rather not know about your DNS resolver in INTERCAL, though ;-) A pure-JS implementation that could run in a browser with WebSockets support would be extra awesome.
A:
The best library I know of (and it includes DNSSEC validation) is libunbound which is part of the Unbound distribution.
Note that the DNS protocol itself does not support your first requirement (multiple queries in one packet). The best you can do is use TCP and then issue multiple sequential queries over one socket.
A:
The DNSSEC-Tools project has a libval C library (and a corresponding perl binding) that supports multi-threaded DNSSEC enabled lookups using their API. It is distributed on many linux platforms and works on most other platforms as well.
(in fact, I'm typing this response in a version of firefox that was linked against the library to provide DNSSEC protection for Firefox).
You can't ask two questions in a single packet though. Everyone else is right about that...
| DNS resolver libraries with support for DNSSEC and/or experimental new RR types | What's the state of the art in DNS resolver libraries? I am particularly interested in full (not stub) resolvers that support any or all of: making multiple queries in one request packet, complete DNSSEC validation, returning detailed information about DNSSEC validation to the application, and can handle experimental new RRs without much hacking. Async queries are nice but not required.
Preferred implementation languages would be C, C++, Python, or Javascript, but I'll look at anything (I'd really rather not know about your DNS resolver in INTERCAL, though ;-) A pure-JS implementation that could run in a browser with WebSockets support would be extra awesome.
| [
"The best library I know of (and it includes DNSSEC validation) is libunbound which is part of the Unbound distribution.\nNote that the DNS protocol itself does not support your first requirement (multiple queries in one packet). The best you can do is use TCP and then issue multiple sequential queries over one so... | [
1,
0
] | [] | [] | [
"c",
"dns",
"javascript",
"python"
] | stackoverflow_0003604814_c_dns_javascript_python.txt |
Q:
As a software developer what is your SNMP suite that easy to integrate into your software
Well, altough the S of the SNMP stands for Simple, yet, so far I haven't experienced it that way. And now that I am about to deploy my software on around around 180 remote Linux servers and wants to monitor the servers and configure my daemons all from a centralized point.
I simply want you to recommend me the library which you'll confidently describe as "SNMP Made Easy".
I am looking for a suite of software which not standing in the developer's way, easy to work with (install, configure).
Speaking from the NOC perspective, the ideal would be such one which requires no maintenance once installed.
Note: Open Source is mandatory.
A:
I wouldn't describe it as easy, but the easiest I've found (quite a while ago) was pysnmp -- I had to wrap it with a couple of façades to make it somewhat usable by people who weren't deep SNMP experts (and that code I had to leave behind at a previous employer, was never open-sourced, and I couldn't reconstruct it right now but would have to develop again from scratch). However, so many years have passed (with PySNMP in continuous development, now with a PSF grant too) that it may definitely have gotten better (one can hope;-).
A:
Try Net-SNMP . It has BSD licence. If you are open for java snmp4j is the best.
A:
I am still searching for that easy to use suite of SNMP tools/API myself.
I build OA&M and I've tried NET-SNMP, Windows SNMP and lately agentpp (www.agentpp.com).
Personally, I preferred the agentpp.
Good luck to you.
A:
The "S" in SNMP is actually for "simple" not because using it is simple, but rather because the protocol (on the wire) is designed to be simple and easy to implement. And it is. Now... actually implementing it and then using it is where the S completely drops away.
| As a software developer what is your SNMP suite that easy to integrate into your software | Well, altough the S of the SNMP stands for Simple, yet, so far I haven't experienced it that way. And now that I am about to deploy my software on around around 180 remote Linux servers and wants to monitor the servers and configure my daemons all from a centralized point.
I simply want you to recommend me the library which you'll confidently describe as "SNMP Made Easy".
I am looking for a suite of software which not standing in the developer's way, easy to work with (install, configure).
Speaking from the NOC perspective, the ideal would be such one which requires no maintenance once installed.
Note: Open Source is mandatory.
| [
"I wouldn't describe it as easy, but the easiest I've found (quite a while ago) was pysnmp -- I had to wrap it with a couple of façades to make it somewhat usable by people who weren't deep SNMP experts (and that code I had to leave behind at a previous employer, was never open-sourced, and I couldn't reconstruct i... | [
3,
2,
0,
0
] | [] | [] | [
"c",
"c++",
"linux",
"python",
"snmp"
] | stackoverflow_0003446087_c_c++_linux_python_snmp.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.