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:
Problems with VLC and instant messaging
I've have asked these questions before with no proper answer. I hope I'll get some response here.
I'm developing an instant messenger in python and I'd like to handle video/audio streaming with VLC. Tha basic idea right now is that in each IM client I'm running one VLC instance that acts as a server that streams to all the users I want, and another VLC instance that's a client and recieves and displays all the streams that other users are sending to me. As you can see, it's kind of a P2P connection and I am having lots of problems.
My first problem was VLC can handle only one stream per port, but I solved this using VLM, the Videolan Manager which allows multiple streams with one instance and on one port.
My second problem was this kind of P2P take has several drawbacks as if someone is behind NAT or a router, you have to do manual configurations to forward the packages from the router to your PC, and it also has another drawback, you can only forward to 1 PC, so you would be able to use the program in only one workstation.
Also, the streams were transported in HTTP protocol, which uses TCP and it's pretty slow. When I tried to do the same with RTSP, I wasn't able to get the stream outside my private LAN.
So, this P2P take is very unlikely to be implemented successfully by an amateur like me, as it has all the typical NAT traversal problems, things that I don't want to mess with as this is not a commercial application, just a school project I must finish in order to graduate as a technician. Finally, I've been recommended to a use a server in a well known IP and that would solve the problem, only one router configuration and let both ends of the conversations be clients. I have no idea how to implement this idea, please any help is useful. Thanks in advance. Sorry for any error, I am not a programming/networking expert nor am I an english-speaking person.
A:
I think they were suggesting you run your program on a LAN which has no ports blocked.
| Problems with VLC and instant messaging | I've have asked these questions before with no proper answer. I hope I'll get some response here.
I'm developing an instant messenger in python and I'd like to handle video/audio streaming with VLC. Tha basic idea right now is that in each IM client I'm running one VLC instance that acts as a server that streams to all the users I want, and another VLC instance that's a client and recieves and displays all the streams that other users are sending to me. As you can see, it's kind of a P2P connection and I am having lots of problems.
My first problem was VLC can handle only one stream per port, but I solved this using VLM, the Videolan Manager which allows multiple streams with one instance and on one port.
My second problem was this kind of P2P take has several drawbacks as if someone is behind NAT or a router, you have to do manual configurations to forward the packages from the router to your PC, and it also has another drawback, you can only forward to 1 PC, so you would be able to use the program in only one workstation.
Also, the streams were transported in HTTP protocol, which uses TCP and it's pretty slow. When I tried to do the same with RTSP, I wasn't able to get the stream outside my private LAN.
So, this P2P take is very unlikely to be implemented successfully by an amateur like me, as it has all the typical NAT traversal problems, things that I don't want to mess with as this is not a commercial application, just a school project I must finish in order to graduate as a technician. Finally, I've been recommended to a use a server in a well known IP and that would solve the problem, only one router configuration and let both ends of the conversations be clients. I have no idea how to implement this idea, please any help is useful. Thanks in advance. Sorry for any error, I am not a programming/networking expert nor am I an english-speaking person.
| [
"I think they were suggesting you run your program on a LAN which has no ports blocked.\n"
] | [
0
] | [] | [] | [
"instant_messaging",
"p2p",
"python",
"streaming",
"vlc"
] | stackoverflow_0004015227_instant_messaging_p2p_python_streaming_vlc.txt |
Q:
AppEngine data strategy to handle a large index per user?
I’m building an AppEngine app in Python.
For the sake of discussion, imagine I’m building a Gmail clone. Except with a million short emails per user.
The point is, each user will have a large search index, all to theirself; just like Gmail, each user has a personal “search engine” of their own content.
Now imagine that many of these messages belong to multiple users (e.g. mailing list emails or cc:ing a hundred users). Not all, but some reasonable fraction.
Without prematurely optimizing, what is my best bet to store the data and the indexes?
A:
How about storing a list of User keys in each mail message? That's assuming that a single message won't be owned by more than a hundred or so users.
class User(db.Model):
"usual properties like name, etc"
class Message(db.Model):
# list of users that have this message
users = db.ListProperty(db.Key)
If you want an unlimited number of user * message relationships, you could use another table:
class UserMessage(db.Model):
user = db.ReferenceProperty(User)
message = db.ReferenceProperty(Message)
here's a couple of good articles on modeling relationships like these on GAE:
http://code.google.com/appengine/articles/modeling.html
http://blog.notdot.net/2010/10/Modeling-relationships-in-App-Engine
A:
class User(db.Model):
pass
class Message(db.Model):
text = db.StringProperty()
class MessageIndex(db.Model): # parent is a Message
users = db.StringListProperty() #users keys
class UserIndex(db.Model): # parent is an User
messages = db.StringListProperty() #messages keys
Take a look here or read the pdf.
| AppEngine data strategy to handle a large index per user? | I’m building an AppEngine app in Python.
For the sake of discussion, imagine I’m building a Gmail clone. Except with a million short emails per user.
The point is, each user will have a large search index, all to theirself; just like Gmail, each user has a personal “search engine” of their own content.
Now imagine that many of these messages belong to multiple users (e.g. mailing list emails or cc:ing a hundred users). Not all, but some reasonable fraction.
Without prematurely optimizing, what is my best bet to store the data and the indexes?
| [
"How about storing a list of User keys in each mail message? That's assuming that a single message won't be owned by more than a hundred or so users.\nclass User(db.Model):\n \"usual properties like name, etc\"\n\nclass Message(db.Model):\n\n # list of users that have this message\n users = db.ListPropert... | [
2,
0
] | [] | [] | [
"database_design",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004120468_database_design_google_app_engine_google_cloud_datastore_python.txt |
Q:
problem with reading RGB values of pixels using pyglet
For a programming project, I need to read pixels from a loaded image using pyglet.
I used "pyglet.image.load('map.png')" to load the image, and I found out that you can retrieve the image data using img.get_image_data().
I use line mapImage.get_region(x,y,1,1).get_image_data().get_data("RGBA", 4)
to read the data from the pixel located at (x,y). This is where I get stuck. When I print the result of the line above, I get an empty space. Could anyone clarify how I extract the RGB values from the string returned by the get_data() function?
Thanks!
A:
Your mapImage... returns a string with 4 characters representing rgba.
Try this:
pix = mapImage.get_region(x,y,1,1).get_image_data().get_data("RGBA", 4)
print 'r = ' + str(ord(pix[0]))
print 'g = ' + str(ord(pix[1]))
print 'b = ' + str(ord(pix[2]))
print 'a = ' + str(ord(pix[3]))
| problem with reading RGB values of pixels using pyglet | For a programming project, I need to read pixels from a loaded image using pyglet.
I used "pyglet.image.load('map.png')" to load the image, and I found out that you can retrieve the image data using img.get_image_data().
I use line mapImage.get_region(x,y,1,1).get_image_data().get_data("RGBA", 4)
to read the data from the pixel located at (x,y). This is where I get stuck. When I print the result of the line above, I get an empty space. Could anyone clarify how I extract the RGB values from the string returned by the get_data() function?
Thanks!
| [
"Your mapImage... returns a string with 4 characters representing rgba.\nTry this:\npix = mapImage.get_region(x,y,1,1).get_image_data().get_data(\"RGBA\", 4)\n\nprint 'r = ' + str(ord(pix[0]))\nprint 'g = ' + str(ord(pix[1]))\nprint 'b = ' + str(ord(pix[2]))\nprint 'a = ' + str(ord(pix[3]))\n\n"
] | [
1
] | [] | [] | [
"pixels",
"pyglet",
"python"
] | stackoverflow_0004200212_pixels_pyglet_python.txt |
Q:
[Python]How to launch a program using Thread
professionals
I know how to launch a command in Linux's terminal via process, sth likes following:
import subprocess
subprocess.Popen('ifconfig -a')
But this is opened in process, how can I launch that in a thread instead?
I know "thread.start_new_thread", while this should call a function. Within the function, I still have to use subprocess. And this just to open a process again..
Thank you for your help.
Respectfully..
A:
A command like ifconfig always runs in a separate process. There is no way to run that command within only a "thread" of your application.
Perhaps you could provide more detail about why you believe this is necessary, and we may be able to suggest a different approach. For example, if you need to capture the output of the ifconfig command, there are certainly ways of doing that within Python.
A:
As you are calling another process outside of your Python application, I think that there is no solution to make it run inside the Python interpreter.
| [Python]How to launch a program using Thread | professionals
I know how to launch a command in Linux's terminal via process, sth likes following:
import subprocess
subprocess.Popen('ifconfig -a')
But this is opened in process, how can I launch that in a thread instead?
I know "thread.start_new_thread", while this should call a function. Within the function, I still have to use subprocess. And this just to open a process again..
Thank you for your help.
Respectfully..
| [
"A command like ifconfig always runs in a separate process. There is no way to run that command within only a \"thread\" of your application.\nPerhaps you could provide more detail about why you believe this is necessary, and we may be able to suggest a different approach. For example, if you need to capture the ou... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004200742_python.txt |
Q:
Does the latest stable pygame release work with python2.7?
Like the subject says: Does the latest stable pygame release work with python2.7?
I've got both versions installed on my OSX Snow Leopard, but import pygame only works on python2.6 - That's the official distro which is 2.6.6, not the pre-installed one which is 2.6.1).
And if it does work, how can I make it work on my machine? What am I doing wrong?
Thanks in advance.
A:
My guess is that you installed it for 2.6 and so it is residing in 2.6's library directory. Install it in 2.7's library directory and you should be good to go. I don't know OSX so I can't help with the details but a little bit of googling shouldn't be too hard. The problem is that the two python installations have distinct import paths.
| Does the latest stable pygame release work with python2.7? | Like the subject says: Does the latest stable pygame release work with python2.7?
I've got both versions installed on my OSX Snow Leopard, but import pygame only works on python2.6 - That's the official distro which is 2.6.6, not the pre-installed one which is 2.6.1).
And if it does work, how can I make it work on my machine? What am I doing wrong?
Thanks in advance.
| [
"My guess is that you installed it for 2.6 and so it is residing in 2.6's library directory. Install it in 2.7's library directory and you should be good to go. I don't know OSX so I can't help with the details but a little bit of googling shouldn't be too hard. The problem is that the two python installations have... | [
0
] | [] | [] | [
"macos",
"pygame",
"python"
] | stackoverflow_0004200644_macos_pygame_python.txt |
Q:
what methods does `foo < bar < baz` actually invoke?
In python we can say:
if foo < bar < baz:
do something.
and similarly, we can overload the comparision operators like:
class Bar:
def __lt__(self, other):
do something else
but what methods of the types of the operands of those interval comparisions are actually called? is the above equivalent to
if foo.__lt__(bar) and bar.__lt__(baz):
do something.
Edit: re S.Lott, Here's some output that helps to illustrate what actually happens.
>>> class Bar:
def __init__(self, name):
self.name = name
print('__init__', self.name)
def __lt__(self, other):
print('__lt__', self.name, other.name)
return self.name < other.name
>>> Bar('a') < Bar('b') < Bar('c')
('__init__', 'a')
('__init__', 'b')
('__lt__', 'a', 'b')
('__init__', 'c')
('__lt__', 'b', 'c')
True
>>> Bar('b') < Bar('a') < Bar('c')
('__init__', 'b')
('__init__', 'a')
('__lt__', 'b', 'a')
False
>>>
A:
if foo < bar < baz:
is equivalent to
if foo < bar and bar < baz:
with one important distinction: if bar is a mutating, it will be cached. I.e.:
if foo < bar() < baz:
is equivalent to
tmp = bar()
if foo < tmp and tmp < baz:
But to answer your question, it will end up being:
if foo.__lt__(bar) and bar.__lt__(baz):
A:
You are correct:
class Bar:
def __init__(self, name):
self.name = name
def __lt__(self, other):
print('__lt__', self.name, other.name)
return True
a,b,c = Bar('a'), Bar('b'), Bar('c')
a < b < c
Output:
('__lt__', 'a', 'b')
('__lt__', 'b', 'c')
True
A:
It uses successive calls to the less-than comparison operator:
>>> import dis
>>> def foo(a,b,c):
... return a < b < c
...
>>> dis.dis(foo)
2 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (b)
6 DUP_TOP
7 ROT_THREE
8 COMPARE_OP 0 (<)
11 JUMP_IF_FALSE 8 (to 22)
14 POP_TOP
15 LOAD_FAST 2 (c)
18 COMPARE_OP 0 (<)
21 RETURN_VALUE
>> 22 ROT_TWO
23 POP_TOP
24 RETURN_VALUE
A:
It calls the special method __lt__(), and if needed it will call __nonzero__() to coerce the result of __lt__() to a boolean. Surprisingly (to me at least), there is no __and__() method to override the and operator.
Here's a test program:
#!/usr/bin/env python
class Bar:
def __init__(self, value):
self.value = value
def __lt__(self, other):
print "%s.__lt__(%s)" % (self, other)
return Bar("%s.__lt__(%s)" % (self, other))
def __nonzero__(self):
print "%s.__nonzero__()" % (self)
return True
def __str__(self):
return self.value
foo = Bar("foo")
bar = Bar("bar")
baz = Bar("baz")
if foo < bar < baz:
pass
Output:
foo.__lt__(bar)
foo.__lt__(bar).__nonzero__()
bar.__lt__(baz)
bar.__lt__(baz).__nonzero__()
| what methods does `foo < bar < baz` actually invoke? | In python we can say:
if foo < bar < baz:
do something.
and similarly, we can overload the comparision operators like:
class Bar:
def __lt__(self, other):
do something else
but what methods of the types of the operands of those interval comparisions are actually called? is the above equivalent to
if foo.__lt__(bar) and bar.__lt__(baz):
do something.
Edit: re S.Lott, Here's some output that helps to illustrate what actually happens.
>>> class Bar:
def __init__(self, name):
self.name = name
print('__init__', self.name)
def __lt__(self, other):
print('__lt__', self.name, other.name)
return self.name < other.name
>>> Bar('a') < Bar('b') < Bar('c')
('__init__', 'a')
('__init__', 'b')
('__lt__', 'a', 'b')
('__init__', 'c')
('__lt__', 'b', 'c')
True
>>> Bar('b') < Bar('a') < Bar('c')
('__init__', 'b')
('__init__', 'a')
('__lt__', 'b', 'a')
False
>>>
| [
"if foo < bar < baz:\n\nis equivalent to\nif foo < bar and bar < baz:\n\nwith one important distinction: if bar is a mutating, it will be cached. I.e.:\nif foo < bar() < baz:\n\nis equivalent to\ntmp = bar()\nif foo < tmp and tmp < baz:\n\nBut to answer your question, it will end up being:\nif foo.__lt__(bar) and b... | [
13,
4,
3,
1
] | [] | [] | [
"operator_overloading",
"python"
] | stackoverflow_0004200822_operator_overloading_python.txt |
Q:
Overriding authenticate method - Django admin
I'm trying to figure out how to enhance the authenticate method with additional functionality.
e.g.
Expiring passwords
special password formats
length requirements
etc...
It is pretty straight forward for the site's frontend, but what about the admin panel?
I reckon that I should override the User's Manager object, as authenticate probably resides there. This is quite a tough one to figure out I think.
Thanks in advance! :)
A:
You can create custom authentication backend by following the instructions in http://docs.djangoproject.com/en/dev/topics/auth/#authentication-backends. Essentially, you create a backend class that has an authenticate method:
class MyBackend:
def authenticate(self, username=None, password=None):
# Check the username/password and return a User.
Then add the class to AUTHENTICATION_BACKENDS in settings.py.
Though this is for authentication, you could do all the password validation things you mentioned simply by redirecting a user to a change password page if the password is correct but expired, for instance. Consider using the messaging framework to give a user a hint about what is going on when directing him to a generic change password page.
A:
If you want the validation for passwords to be built into the model, then you'll probably want to extend the django User model.
Otherwise, you could do the following:
override admin password options by creating your own views for changing and setting passwords, then putting the relevant URLS just above (r'^admin/', include(admin.site.urls)). Regex would look something like (r'^admin/auth/user/(\d+)/password/', new_change_password).
Keep track of password age in a separate model and then when they expire, redirect to a change password once it expires.
| Overriding authenticate method - Django admin | I'm trying to figure out how to enhance the authenticate method with additional functionality.
e.g.
Expiring passwords
special password formats
length requirements
etc...
It is pretty straight forward for the site's frontend, but what about the admin panel?
I reckon that I should override the User's Manager object, as authenticate probably resides there. This is quite a tough one to figure out I think.
Thanks in advance! :)
| [
"You can create custom authentication backend by following the instructions in http://docs.djangoproject.com/en/dev/topics/auth/#authentication-backends. Essentially, you create a backend class that has an authenticate method:\nclass MyBackend:\n def authenticate(self, username=None, password=None):\n # C... | [
6,
0
] | [] | [] | [
"django",
"django_admin",
"django_authentication",
"django_models",
"python"
] | stackoverflow_0004197389_django_django_admin_django_authentication_django_models_python.txt |
Q:
python script output to webpage
I wrote a python script that reads in text from a file and writes a text file of definitions. I want to somehow integrate my program with a webpage for the whole world to see.
I want to be able to retrieve input text from one text box, have the python script process it, then display the output in the other text box.
I have done quite a bit of research thus far but I am still unsure of the best way to go about doing this. I tried using google's app engine but encountered too many problems, for example the app engine runtime environment uses python 2.5.2, I wrote my program using 3.1.2. Other than that I just felt that I was beginning to waste my time trying to port my program over.
I'm starting to think that javascript is the way to go or maybe pyjamas. I was also wondering if it would be possible to just have the python program constantly running on the server and to perform a system call.
I posses very little knowledge when it comes to web development. I appreciate any advice.
A:
It's a much bigger question, involving:
Where are you going to host the site,
How slow is the script (can it execute in a few seconds or not),
Does it need access data from files or a database,
How complex is it,
etc.
I would suggest you read about Django:
http://docs.djangoproject.com/en/1.2/
That is probably the easiest way to set up a simple web site, but is also very powerful if you want to do something more in the future (related to this project or not).
However, since your script is Python 3 only, you don't have too many options, see this question:
https://stackoverflow.com/questions/373945/what-web-development-frameworks-support-python-3
I suppose, if not too hard, it is worth thinking about converting it to Python 2.7.
If that is an option, then you might very well go down to Python 2.5 and use Google App Engine. It gives you many things for free and you really don't need to worry about many things that you would if you were to set up your server. It includes a modified (better to say, shrunk down) version of Django 1.1. When you say you are wasting your time porting from 3.x to 2.5, I guess you were not counting the time that you will waste setting all other things up.
A:
You could use the cgi module and create a CGI script, if your server supports it.
| python script output to webpage | I wrote a python script that reads in text from a file and writes a text file of definitions. I want to somehow integrate my program with a webpage for the whole world to see.
I want to be able to retrieve input text from one text box, have the python script process it, then display the output in the other text box.
I have done quite a bit of research thus far but I am still unsure of the best way to go about doing this. I tried using google's app engine but encountered too many problems, for example the app engine runtime environment uses python 2.5.2, I wrote my program using 3.1.2. Other than that I just felt that I was beginning to waste my time trying to port my program over.
I'm starting to think that javascript is the way to go or maybe pyjamas. I was also wondering if it would be possible to just have the python program constantly running on the server and to perform a system call.
I posses very little knowledge when it comes to web development. I appreciate any advice.
| [
"It's a much bigger question, involving:\n\nWhere are you going to host the site, \nHow slow is the script (can it execute in a few seconds or not), \nDoes it need access data from files or a database,\nHow complex is it,\netc.\n\nI would suggest you read about Django:\n\nhttp://docs.djangoproject.com/en/1.2/\n\nTh... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004201405_python.txt |
Q:
Using lxml to extract data where all elements are not known in advance
I have some sgml files that are roughly standardized. However, there can be data contained within a tag that I do not know exists before I open the file and personally read it. For example, the files have addresses and generally the addresses have a street, a city, a state, a zip and a phone. Each element of the address is indicated with a tag
<ADDRESS>
<STREET>One Main Street
<CITY>Gotham City
<ZIP>99999 0123
<PHONE>555-123-5467
</ADDRESS>
But, for example, I have discovered that there are tags for Country, STREET1, STREET2. I have over 200K files to process and I want know if it is possible to pull out all of the elements of the addresses without having to worry about knowing the existence of unknown tags.
What I have done so far is
h=fromstring(my_data_in_a_string)
for each in h.cssselect('mail_address'):
each.text_content()
but what I get is problematic because I can't identify where one element ends and the next begins
One Main StreetGotham City99999 0123555-123-5467
A:
To get all the tags, we iter through the document like this:
Suppose your XML structure is like this:
<ADDRESS>
<STREET>One Main Street</STREET>
<CITY>Gotham City</CITY>
<ZIP>99999 0123</ZIP>
<PHONE>555-123-5467</PHONE>
</ADDRESS>
We parse it:
>>> from lxml import etree
>>> f = etree.parse('foo.xml') # path to XML file
>>> root = f.getroot() # get the root element
>>> for tags in root.iter(): # iter through the root element
... print tags.tag # print all the tags
...
ADDRESS
STREET
CITY
ZIP
PHONE
Now suppose your XML has extra tags as well; tags you are not aware about. Since we are iterating through the XML, the above code will return those tags as well.
<ADDRESS>
<STREET>One Main Street</STREET>
<STREET1>One Second Street</STREET1>
<CITY>Gotham City</CITY>
<ZIP>99999 0123</ZIP>
<PHONE>555-123-5467</PHONE>
<COUNTRY>USA</COUNTRY>
</ADDRESS>
The above code returns:
ADDRESS
STREET
STREET1
CITY
ZIP
PHONE
COUNTRY
Now if we want to get the text of the tags, the procedure is the same. Just print tag.text like this:
>>> for tags in root.iter():
... print tags.text
...
One Main Street
One Second Street
Gotham City
99999 0123
555-123-5467
USA
| Using lxml to extract data where all elements are not known in advance | I have some sgml files that are roughly standardized. However, there can be data contained within a tag that I do not know exists before I open the file and personally read it. For example, the files have addresses and generally the addresses have a street, a city, a state, a zip and a phone. Each element of the address is indicated with a tag
<ADDRESS>
<STREET>One Main Street
<CITY>Gotham City
<ZIP>99999 0123
<PHONE>555-123-5467
</ADDRESS>
But, for example, I have discovered that there are tags for Country, STREET1, STREET2. I have over 200K files to process and I want know if it is possible to pull out all of the elements of the addresses without having to worry about knowing the existence of unknown tags.
What I have done so far is
h=fromstring(my_data_in_a_string)
for each in h.cssselect('mail_address'):
each.text_content()
but what I get is problematic because I can't identify where one element ends and the next begins
One Main StreetGotham City99999 0123555-123-5467
| [
"To get all the tags, we iter through the document like this:\nSuppose your XML structure is like this:\n<ADDRESS>\n <STREET>One Main Street</STREET>\n <CITY>Gotham City</CITY>\n <ZIP>99999 0123</ZIP>\n <PHONE>555-123-5467</PHONE>\n </ADDRESS>\n\nWe parse it:\n>>> from lxml import etree\n>>> f = etree.parse('foo.xm... | [
2
] | [] | [] | [
"lxml",
"parsing",
"python",
"sgml"
] | stackoverflow_0004201562_lxml_parsing_python_sgml.txt |
Q:
Ubuntu:What is the right way to reinstall from source after package was installed via apt?
I have a python package previously installed via apt(by default).
Now I want to install new version and compile it manually from the sources with all the required modules.
How can I do that?
I suppose that
apt-get purge python
And then install from sources is not possible because python have lots of dependencies and will uninstall all of them in this case.
What is the right way to do that?
A:
Don't replace your system's default Python interpreter. It can break things which will be difficult to fix later. Instead you probably want to use virtualenv. You can then isolate any issues from your environment and have the added advantage of multiple Python installations which can tested independently.
Here is some worthwhile reading to get you started:
http://www.lorenzogil.com/blog/2010/10/29/python-deployment-tips/
http://mitchfournier.com/2010/06/25/getting-started-with-virtualenv-isolated-python-environments/
http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip
| Ubuntu:What is the right way to reinstall from source after package was installed via apt? | I have a python package previously installed via apt(by default).
Now I want to install new version and compile it manually from the sources with all the required modules.
How can I do that?
I suppose that
apt-get purge python
And then install from sources is not possible because python have lots of dependencies and will uninstall all of them in this case.
What is the right way to do that?
| [
"Don't replace your system's default Python interpreter. It can break things which will be difficult to fix later. Instead you probably want to use virtualenv. You can then isolate any issues from your environment and have the added advantage of multiple Python installations which can tested independently. \nHer... | [
1
] | [
"sudo apt-get remove name-of-package\n\nthen\nsudo apt-get autoclean\n\nwill remove the package and any dependencies that are no longer needed.\n"
] | [
-3
] | [
"compilation",
"debian",
"installation",
"python",
"ubuntu"
] | stackoverflow_0004199894_compilation_debian_installation_python_ubuntu.txt |
Q:
In django, how can I retrieve a value from db into a custom field template?
I am using a custom class on my model to provide image uploading, through an app called django-filebrowser.
# myapp/models.py
class Book(models.Model):
name = models.CharField(max_length=30)
image = FileBrowseField("Image", max_length=200, blank=True, null=True)
...
The model uses filebrowser's custom field "FileBrowserField", which adds a link to a separate upload page (http://site/admin/filebrowser/browse/?ot=desc&o=date). What I'd like to do is to tweak the custom form's template to add a "dir" parameter, like so: (http://site/admin/filebrowser/browse/?ot=desc&o=date&dir=book1). book1, in this case, would be retrieved from the "name" CharField of this Book.
I know that the template that I want to modify is rendered by filebrowser's fields.py, and there is a variable that sets the "dir" parameter, but I don't know how to fetch the string value from my own model to fields.py so I can set this variable. Does anyone have any suggestions?
A:
Found a solution elsewhere, so I thought I'd share it:
# models.py
class Book(models.Model):
name = models.CharField(max_length=30)
image = FileBrowseField("Image", max_length=200, blank=True, null=True)
...
def __init__(self, *args, **kargs):
super(Property, self).__init__(*args, **kargs)
self._meta.get_field_by_name("image")[0].directory = self.name
| In django, how can I retrieve a value from db into a custom field template? | I am using a custom class on my model to provide image uploading, through an app called django-filebrowser.
# myapp/models.py
class Book(models.Model):
name = models.CharField(max_length=30)
image = FileBrowseField("Image", max_length=200, blank=True, null=True)
...
The model uses filebrowser's custom field "FileBrowserField", which adds a link to a separate upload page (http://site/admin/filebrowser/browse/?ot=desc&o=date). What I'd like to do is to tweak the custom form's template to add a "dir" parameter, like so: (http://site/admin/filebrowser/browse/?ot=desc&o=date&dir=book1). book1, in this case, would be retrieved from the "name" CharField of this Book.
I know that the template that I want to modify is rendered by filebrowser's fields.py, and there is a variable that sets the "dir" parameter, but I don't know how to fetch the string value from my own model to fields.py so I can set this variable. Does anyone have any suggestions?
| [
"Found a solution elsewhere, so I thought I'd share it:\n# models.py\nclass Book(models.Model):\n name = models.CharField(max_length=30)\n image = FileBrowseField(\"Image\", max_length=200, blank=True, null=True)\n\n...\n\n def __init__(self, *args, **kargs): ... | [
2
] | [] | [] | [
"django",
"django_filebrowser",
"django_models",
"python"
] | stackoverflow_0004194041_django_django_filebrowser_django_models_python.txt |
Q:
When does Python do automatic type conversion?
When does Python do automatic type conversion?
--
Update:
I asked this after reading this post: In praise of Go or : "Why I moved from Python and C++ to Go". The one of the points the poster makes is that:
It is statically typed, so it is more explicit and the code of a third
party is more readable. Also it
eliminates the risk of unwanted
automatic type conversions (unlike
Python).
I had no idea what he meant by "unwanted automatic type conversions". Now, I think he's talking about implicit numeric conversions. Of course, Python has these as 1.0 + 2 will convert 2 to 2.0 and return 3.0.
A:
It doesn't - it has duck typing instead.
(I may have misunderstood what you meant by automatic type conversion, though, so it would help if you give more detail in your question.)
| When does Python do automatic type conversion? | When does Python do automatic type conversion?
--
Update:
I asked this after reading this post: In praise of Go or : "Why I moved from Python and C++ to Go". The one of the points the poster makes is that:
It is statically typed, so it is more explicit and the code of a third
party is more readable. Also it
eliminates the risk of unwanted
automatic type conversions (unlike
Python).
I had no idea what he meant by "unwanted automatic type conversions". Now, I think he's talking about implicit numeric conversions. Of course, Python has these as 1.0 + 2 will convert 2 to 2.0 and return 3.0.
| [
"It doesn't - it has duck typing instead.\n(I may have misunderstood what you meant by automatic type conversion, though, so it would help if you give more detail in your question.)\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004201941_python.txt |
Q:
Is it good form to have an __init__ method that checks the type of its input?
I have a class that wants to be initialized from a few possible inputs. However a combination of no function overloading and my relative inexperience with the language makes me unsure of how to proceed. Any advice?
A:
Check out this question asked earlier.
In short, the recommendation is that you use classmethods or isinstance(), with classmethods being heavily favored.
A:
With Python, you should use duck typing. Wikipedia has a good section on its use in Python at http://en.wikipedia.org/wiki/Duck_typing#In_Python
A:
Contrary to what others have answered, it's not rare to check for types in __init__. For example the array.array class in the Python Standard library accepts an optional initializer argument, which may be a list, string, or iterable. The documentation explicitly states different actions take place based on the type. For another example of the same treatment by argument type see decimal.Decimal. Or see zipfile.Zipfile, which accepts a file argument "where file can be either a path to a file (a string) or a file-like object." (Here we see both explicit type checking (a string) and duck typing (a file-like object) all in one!)
If you find explicit type checking in __init__ is getting messy, try a different approach. Use factory functions instead. For example, let's say you have a triangle module with a Triangle class. There are many ways to construct a triangle. Rather than having __init__ handle all these ways, you could add factory methods to your module:
triangle.from_sas(side1, angle, side2)
triangle.from_asa(angle1, side, angle2)
triangle.from_sss(side1, side2, side3)
triangle.from_aas(angle1, angle2, side)
These factory methods could also be rolled into the Triangle class, using the @classmethod decorator. For an excellent example of this technique see Thomas Wouter's fine answer to stackoverflow question overloading init in python.
A:
No, don't check for types explicitly. Python is a duck typed language. If the wrong type is passed, a TypeError will be raised. That's it. You need not bother about the type, that is the responsibility of the programmer.
| Is it good form to have an __init__ method that checks the type of its input? | I have a class that wants to be initialized from a few possible inputs. However a combination of no function overloading and my relative inexperience with the language makes me unsure of how to proceed. Any advice?
| [
"Check out this question asked earlier.\nIn short, the recommendation is that you use classmethods or isinstance(), with classmethods being heavily favored.\n",
"With Python, you should use duck typing. Wikipedia has a good section on its use in Python at http://en.wikipedia.org/wiki/Duck_typing#In_Python\n",
"... | [
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004201590_python.txt |
Q:
Python auto completing directory when I press tab (./)
I have a rather peculiar problem, when i'm working on Python in Max OSX terminal, my tab key no longer indents, it now inserts a ./
It seems it is auto-completing directories, if I press tab twice it lists directories, if i type in part of a directory and press tab it autocompletes. I understand this is a standard function in terminal, but not supposed to happen in the Python interpreter? The same thing happens when I run Python in x11.
I have no idea what I did to cause this, the change seemed to happen while I was in Python's help function. I may have pressed a certain combination of keys to activate it, but have no idea what it was. Furthermore google searches aren't returning anyone with the same issue.
I would really appreciate some help here, I'm a beginning computer science student and not being able to tab in Python is pretty frustrating :P
A:
It's a bug; see here for details. Most likely you are using the Python 2.7 from the python.org OS X 32-bit/64-bit installer for 10.5 and above or you are using a Python 2.7 or 3.2alpha built from source. If you are using 2.7, the easiest workaround is to install the other python.org OS X installer: the one for 32-bit for 10.3 and above.
UPDATE: The fix for this problem is included as of the Python 2.7.2 and the 3.2 python.org installers and, apparently, in Apple's 2.7.1 system Python in OS X 10.7.
| Python auto completing directory when I press tab (./) | I have a rather peculiar problem, when i'm working on Python in Max OSX terminal, my tab key no longer indents, it now inserts a ./
It seems it is auto-completing directories, if I press tab twice it lists directories, if i type in part of a directory and press tab it autocompletes. I understand this is a standard function in terminal, but not supposed to happen in the Python interpreter? The same thing happens when I run Python in x11.
I have no idea what I did to cause this, the change seemed to happen while I was in Python's help function. I may have pressed a certain combination of keys to activate it, but have no idea what it was. Furthermore google searches aren't returning anyone with the same issue.
I would really appreciate some help here, I'm a beginning computer science student and not being able to tab in Python is pretty frustrating :P
| [
"It's a bug; see here for details. Most likely you are using the Python 2.7 from the python.org OS X 32-bit/64-bit installer for 10.5 and above or you are using a Python 2.7 or 3.2alpha built from source. If you are using 2.7, the easiest workaround is to install the other python.org OS X installer: the one for 3... | [
1
] | [] | [] | [
"autocomplete",
"macos",
"python",
"tabs",
"terminal"
] | stackoverflow_0004201791_autocomplete_macos_python_tabs_terminal.txt |
Q:
win32: get current DEVMODE of a monitor
How can I get the current resolution in win32? I know I can use GetMonitorInfo to get the current bounding rectangle of the monitor, but how can I also get the bit-depth? Pretty much, how do I get the DEVMODE struct of a given monitor?
I'm using python and pywin32, so solutions addressing those specifically are nice, but just the winapi calls will do.
A:
In addition to the EnumDisplayMonitors function mentioned in Dean's answer you need GetDeviceCaps(). See parameter BITSPIXEL: it gives you the number of adjacent color bits for each pixel.
A:
You'll want to use the EnumDisplayMonitors function, which calls a callback for each monitor and passes the rectangle and a device context (which includes the colour information).
pywin32 has win32api.EnumDisplayMonitors, which appears to use EnumDisplayMonitors under the covers to return a list with the same details as I mentioned above.
| win32: get current DEVMODE of a monitor | How can I get the current resolution in win32? I know I can use GetMonitorInfo to get the current bounding rectangle of the monitor, but how can I also get the bit-depth? Pretty much, how do I get the DEVMODE struct of a given monitor?
I'm using python and pywin32, so solutions addressing those specifically are nice, but just the winapi calls will do.
| [
"In addition to the EnumDisplayMonitors function mentioned in Dean's answer you need GetDeviceCaps(). See parameter BITSPIXEL: it gives you the number of adjacent color bits for each pixel.\n",
"You'll want to use the EnumDisplayMonitors function, which calls a callback for each monitor and passes the rectangle a... | [
1,
0
] | [] | [] | [
"monitor",
"python",
"pywin32",
"winapi"
] | stackoverflow_0004200560_monitor_python_pywin32_winapi.txt |
Q:
python 3: how to check if an object is a function?
Am I correct assuming that all functions (built-in or user-defined) belong to the same class, but that class doesn't seem to be bound to any variable by default?
How can I check that an object is a function?
I can do this I guess:
def is_function(x):
def tmp()
pass
return type(x) is type(tmp)
It doesn't seem neat, and I'm not even 100% sure it's perfectly correct.
A:
in python2:
callable(fn)
in python3:
isinstance(fn, collections.Callable)
as Callable is an Abstract Base Class, this is equivalent to:
hasattr(fn, '__call__')
A:
How can I check that an object is a function?
Isn't this same as checking for callables
hasattr(object, '__call__')
and also in python 2.x
callable(object) == True
A:
You can do:
def is_function(x):
import types
return isinstance(x, types.FunctionType) \
or isinstance(x, types.BuiltinFunctionType)
| python 3: how to check if an object is a function? | Am I correct assuming that all functions (built-in or user-defined) belong to the same class, but that class doesn't seem to be bound to any variable by default?
How can I check that an object is a function?
I can do this I guess:
def is_function(x):
def tmp()
pass
return type(x) is type(tmp)
It doesn't seem neat, and I'm not even 100% sure it's perfectly correct.
| [
"in python2:\ncallable(fn)\n\nin python3:\nisinstance(fn, collections.Callable)\n\nas Callable is an Abstract Base Class, this is equivalent to:\nhasattr(fn, '__call__')\n\n",
"\nHow can I check that an object is a function?\n\nIsn't this same as checking for callables\nhasattr(object, '__call__')\n\nand also in ... | [
24,
5,
3
] | [
"try:\n magicVariable()\nexcept TypeError as e:\n print( 'was no function' )\n\n"
] | [
-4
] | [
"class",
"function",
"python",
"python_3.x"
] | stackoverflow_0004202301_class_function_python_python_3.x.txt |
Q:
xml file encryption with Python
i am making a mail client and i have made an option in which user can save his/her profile
and i saving all details in an xml file using SXML lib in python . now i want that file to be encrypted otherwise any one can see the details...How do i Do dat?
A:
I have been using a Recipe from Active state for some time, you can find stronger algorithms but if you just need to keep away the curious it will be ok :)
If you really need a higher degree of confidence you can try pyDES and use a TripleDES for the encryptation.
TripleDES
A:
An easy way:
Accept the password from the user and then store it use base64.
>>> import base64
>>> print base64.b64encode("password")
cGFzc3dvcmQ=
>>> print base64.b64decode("cGFzc3dvcmQ=")
password
So encode the password and save it in the XML file and then when you want to read from it, decode it.
DOCS
PS: I am not saying this is highly secure, but still this will suffice for a casual glance at the file. Again if you need it to be really secure (is that even possible?), then you should find something else. This solution is more about being obscure.
| xml file encryption with Python | i am making a mail client and i have made an option in which user can save his/her profile
and i saving all details in an xml file using SXML lib in python . now i want that file to be encrypted otherwise any one can see the details...How do i Do dat?
| [
"I have been using a Recipe from Active state for some time, you can find stronger algorithms but if you just need to keep away the curious it will be ok :)\nIf you really need a higher degree of confidence you can try pyDES and use a TripleDES for the encryptation.\nTripleDES\n",
"An easy way:\nAccept the passwo... | [
1,
0
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0004202577_encryption_python.txt |
Q:
Is there an include file for class statements in python?
I think this is almost certainly a very basic question but I'm struggling with it. I have 2 python files, one for the main content on my site and one for the admin area. You can see the two files here:
https://gist.github.com/670034
In both these files I define the classes and import the necessary modules at the top and if I change in one file I need to remember to change in the other file. Is there a way to define all these in one file and then include this for both files?
I'm sure there is an easy way of doing this but I can't seem to find how to do it.
Thanks
Tom
A:
Just create a file, like myimports.py:
import cgi
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.datastore import entity_pb
Then you can do:
from myimports import *
Note that while this saves space, it doesn't make it more readable as you need to check the additional file just to see what you imported.
A:
Echoing what poke says, it's maybe better not to make your imports in a centralised place as you can end up losing fine grained control over what is in your namespace. I know this does not answer your question, but it may help in the long run.
A:
Create new module:
import some
class A:
pass
and import module in the both files:
import new_module
A:
Define the classes in a separate file and import it in the other two.
| Is there an include file for class statements in python? | I think this is almost certainly a very basic question but I'm struggling with it. I have 2 python files, one for the main content on my site and one for the admin area. You can see the two files here:
https://gist.github.com/670034
In both these files I define the classes and import the necessary modules at the top and if I change in one file I need to remember to change in the other file. Is there a way to define all these in one file and then include this for both files?
I'm sure there is an easy way of doing this but I can't seem to find how to do it.
Thanks
Tom
| [
"Just create a file, like myimports.py:\nimport cgi\nimport os\n\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom google.appengine.a... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004202844_python.txt |
Q:
Extending Python with C++ no SWIG
OK so I have a C++ function with a header like this:
int myfunc(vector<int> a, vector<mystruct> b, vector<int> c)
I have written the wrapper code (using Python.h as I have done many times with C, which translates the Python data types into the vector datatypes and structs I use in my program). The problem is I don't know how to tell setup.py to compile it with g++, I get a bunch of errors when I run
setup.py build -i
My setup.py:
from distutils.core import setup, Extension
setup(name="MyModule", version="1.0",
ext_modules=[Extension("MyModule", ["myfunc.cpp"])])
Can anyone tell me how I can make the build process use g++ a not gcc
A:
You should add language="c++" to your Extension object:
Extension("MyModule", ["myfunc.cpp"], language="c++")
| Extending Python with C++ no SWIG | OK so I have a C++ function with a header like this:
int myfunc(vector<int> a, vector<mystruct> b, vector<int> c)
I have written the wrapper code (using Python.h as I have done many times with C, which translates the Python data types into the vector datatypes and structs I use in my program). The problem is I don't know how to tell setup.py to compile it with g++, I get a bunch of errors when I run
setup.py build -i
My setup.py:
from distutils.core import setup, Extension
setup(name="MyModule", version="1.0",
ext_modules=[Extension("MyModule", ["myfunc.cpp"])])
Can anyone tell me how I can make the build process use g++ a not gcc
| [
"You should add language=\"c++\" to your Extension object:\nExtension(\"MyModule\", [\"myfunc.cpp\"], language=\"c++\")\n\n"
] | [
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0004202627_c++_python.txt |
Q:
Is it worth learning C/C++ before learning Python?
I want to learn python, but I feel I should learn C or C++ to get a solid base to build on. I already know some C/C++ as well as other programming languages, which does help. So, should I master C/C++ first?
A:
In my opinion it's better to start learning Python.
I found it easier to learn then C or C++. It has libraries to do virtually anything you might need, and can do essentially anything.
The only reason to use a more difficult language like C/C++ is if you need the performance or are writing code for an embedded system. They are not, however, what you should be learning initially.
C# is a fine language, but nothing beats Python for ease of use.
The scope of Python is quite broad, here are some examples:
Create a website (Django, etc.)
Create scripts to do tasks ranging from image manipulation to server maintenance
Create GUIs (Tkinter, etc.)
Create games (pygame)
Scientific computing (SciPy)
Python can interact directly with arbitrary C code, meaning anything which can be done in C, can be done in Python with a little work. Python is popular enough that an interface has been created for virtually everything already.
For a better look at what can be done with python out of the box, take a look at the standard library which comes with python: http://docs.python.org/library/
In short, if it can be done with a computer, and doesn't require the speed of C/C++, it can be done with Python.
A:
I would say it depends on what you want to achieve (cheesy answer...)
The truth is, learning language is a long process. If you plan on learning a language as a step toward learning another language, you're probably wasting your time.
It takes a good year to be proficient with C++, and that is with basic knowledge of algorithms and object concepts. And I only mean proficient, meaning you can get things done, but certainly not expert or anything.
So the real question is, do you want to spend a year learning C++ before beginning to learn Python ?
If the ultimate goal is to program in Python... it doesn't seem worth it.
A:
Real mastery of a language takes time and lots of practice .. its analogous to learning a natural language like French . you have to do a lot of practice in it. but then different languages teach you different programming methodologies.
python and c++ are all object oriented languages so you will be learning the same programming methodology
The order in which you learn languages doesn't really matter but starting from a lower abstraction to higher one makes understanding some things easier..
A:
In my opinion you should defiantly learn Python before attempting to learn C or C++ as you will get a better understanding of the core concepts, C++ is mush lower level than Python so you will need to make more commands to do something that you can do in one line in python.
| Is it worth learning C/C++ before learning Python? | I want to learn python, but I feel I should learn C or C++ to get a solid base to build on. I already know some C/C++ as well as other programming languages, which does help. So, should I master C/C++ first?
| [
"In my opinion it's better to start learning Python. \nI found it easier to learn then C or C++. It has libraries to do virtually anything you might need, and can do essentially anything.\nThe only reason to use a more difficult language like C/C++ is if you need the performance or are writing code for an embedded ... | [
7,
4,
2,
1
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0004202455_c_c++_python.txt |
Q:
Python exception:"TypeError: main() got an unexpected keyword argument 'debug'" but IFF the module is run via scheduledTask on Windows XP SP2
Running Python 2.5 on Windows XP SP2.
When I run a Python script that calls a user-defined module called Zipper.py (basically a wrapper for a zipfile) using a Windows scheduledTask I get this exception:
Traceback (most recent call last):
File "C:\PythonScripts\ZipAndSendEOD-Reports.py", line 78, in main
Zipper.main([report],f, debug=True) #[:-4] + "_" + str(x) + ".zip")
TypeError: main() got an unexpected keyword argument 'debug'
The odd thing is that if I simply open the file in IDLE and hit 'F5', it runs flawlessly.
I'm sure I left out some pertinent information, please let me know what you need.
Zipper.py looks like this:
import zipfile
def main(archive_list=[],zfilename='default.zip', debug=False):
if debug: print 'file to zip', zfilename
zout = zipfile.ZipFile(zfilename, "w", zipfile.ZIP_DEFLATED)
for fname in archive_list:
if debug: print "writing: ", fname
zout.write(fname)
zout.close()
if __name__ == '__main__':
main()
EDIT:
I added the following two lines of code to the calling function, and it now works.
f = open(logFile, 'a')
f.write(Zipper.__file__)
Can you explain THAT to me?
A:
As Paul said, you're probably running a different version of Zipper.py - I would print out Zipper.__file__ and then if you need to debug, print out sys.path to see why it's finding a different file.
| Python exception:"TypeError: main() got an unexpected keyword argument 'debug'" but IFF the module is run via scheduledTask on Windows XP SP2 | Running Python 2.5 on Windows XP SP2.
When I run a Python script that calls a user-defined module called Zipper.py (basically a wrapper for a zipfile) using a Windows scheduledTask I get this exception:
Traceback (most recent call last):
File "C:\PythonScripts\ZipAndSendEOD-Reports.py", line 78, in main
Zipper.main([report],f, debug=True) #[:-4] + "_" + str(x) + ".zip")
TypeError: main() got an unexpected keyword argument 'debug'
The odd thing is that if I simply open the file in IDLE and hit 'F5', it runs flawlessly.
I'm sure I left out some pertinent information, please let me know what you need.
Zipper.py looks like this:
import zipfile
def main(archive_list=[],zfilename='default.zip', debug=False):
if debug: print 'file to zip', zfilename
zout = zipfile.ZipFile(zfilename, "w", zipfile.ZIP_DEFLATED)
for fname in archive_list:
if debug: print "writing: ", fname
zout.write(fname)
zout.close()
if __name__ == '__main__':
main()
EDIT:
I added the following two lines of code to the calling function, and it now works.
f = open(logFile, 'a')
f.write(Zipper.__file__)
Can you explain THAT to me?
| [
"As Paul said, you're probably running a different version of Zipper.py - I would print out Zipper.__file__ and then if you need to debug, print out sys.path to see why it's finding a different file.\n"
] | [
3
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0004199535_exception_python.txt |
Q:
Using Elmer to execute Python in TCL; how do I handle keyword arguments?
I have a Python class that looks like this:
class Mine:
def __init__ (self, param1=None, param2=None, param3=None):
self.param1 = param1
self.param2 = param2
self.param3 = param3
What should my Elmer glue file look like for this class? If they were all strings, I would guess this:
class Mine {
Mine __init__ ( string, string, string ) -> create
But what if param3 is an object? Or a dictionary?
And is there any chance that Elmer supports **kwarg:
class Mine2:
def __init__ (self, param1=None, param2=None, **kwargs):
self.param1 = param1
self.param2 = param2
self.kwargs = kwargs
Thanks.
A:
Reading the elmer docs, I'd guess that you'd be best off using the guess type as it usually “does the right thing” (and you'll have to specify them all when doing the call).
I don't know how it handles defaulted arguments or keyword lists; the documentation doesn't say at all (but looking at the code, I'd say that it doesn't handle keyword lists well). You might want to contact the author of elmer for more advice on this…
| Using Elmer to execute Python in TCL; how do I handle keyword arguments? | I have a Python class that looks like this:
class Mine:
def __init__ (self, param1=None, param2=None, param3=None):
self.param1 = param1
self.param2 = param2
self.param3 = param3
What should my Elmer glue file look like for this class? If they were all strings, I would guess this:
class Mine {
Mine __init__ ( string, string, string ) -> create
But what if param3 is an object? Or a dictionary?
And is there any chance that Elmer supports **kwarg:
class Mine2:
def __init__ (self, param1=None, param2=None, **kwargs):
self.param1 = param1
self.param2 = param2
self.kwargs = kwargs
Thanks.
| [
"Reading the elmer docs, I'd guess that you'd be best off using the guess type as it usually “does the right thing” (and you'll have to specify them all when doing the call).\nI don't know how it handles defaulted arguments or keyword lists; the documentation doesn't say at all (but looking at the code, I'd say tha... | [
0
] | [] | [] | [
"python",
"tcl"
] | stackoverflow_0004199053_python_tcl.txt |
Q:
CSS compilers in GAE Python
Are there any quick light python libraries to use compiled CSS that is converted to CSS on-the-fly?
A:
You can try CleverCSS:
http://sandbox.pocoo.org/clevercss/
Or the Python port of LessCSS: http://code.google.com/p/lesscss-python/
The Python version of LessCSS is quite new though, it doesn't seem to be all that mature yet.
| CSS compilers in GAE Python | Are there any quick light python libraries to use compiled CSS that is converted to CSS on-the-fly?
| [
"You can try CleverCSS:\nhttp://sandbox.pocoo.org/clevercss/\nOr the Python port of LessCSS: http://code.google.com/p/lesscss-python/\nThe Python version of LessCSS is quite new though, it doesn't seem to be all that mature yet.\n"
] | [
1
] | [] | [] | [
"css",
"google_app_engine",
"python"
] | stackoverflow_0004203127_css_google_app_engine_python.txt |
Q:
django select widget doesnt update when i pass the choices into it
so im trying to update in my view a select widget as part of a form.
i'e seen tons of stuff on how to do it, i've followed it and got nearly there.
i've got a bit of code below which is called to populate the select with the choices and it does, but i think the formatting is out, as its passing back a unicode string and i think it needs to be a tuple.
assigning the choices
form.fields['size_option'].widget.attrs['choices'] = Product.get_options(product)
the code that generates the choices
def get_options(self):
optionset = "("
for option in self.optionset.options.all():
optionset = optionset + "(\'" + option.name + "\', \'" + option.name + "\')"
optionset = optionset + ")"
pdb.set_trace()
return optionset
the html generated for the select is below.
<select id="id_size_option" name="size_option" choices="(('Small', 'Small')('Medium', 'Medium')('Large', 'Large'))">
so the problem is probably the optionset passed back. i can guess as much. i just don't know whats wrong with it. i cant find documentation that shows how this should be formatted inside the select.
A:
What is this supposed to be doing? The format for a list of choices is a standard tuple:
CHOICES = (
('x', 'choice x'),
('y', 'choice y'),
)
so I don't understand what you are trying to do with all that string formatting.
Secondly, choices is not an element of the widget's attrs, it is an attribute of the field and/or the widget itself:
form.fields['size_option'].choices = product.get_options()
In any case, you probably want to use a ModelChoiceField here, then you can set the queryset attribute to the list of options you want.
Finally, you don't call an instance method with Class.method(instance), you call it with instance.method() - in your case, product.get_options().
| django select widget doesnt update when i pass the choices into it | so im trying to update in my view a select widget as part of a form.
i'e seen tons of stuff on how to do it, i've followed it and got nearly there.
i've got a bit of code below which is called to populate the select with the choices and it does, but i think the formatting is out, as its passing back a unicode string and i think it needs to be a tuple.
assigning the choices
form.fields['size_option'].widget.attrs['choices'] = Product.get_options(product)
the code that generates the choices
def get_options(self):
optionset = "("
for option in self.optionset.options.all():
optionset = optionset + "(\'" + option.name + "\', \'" + option.name + "\')"
optionset = optionset + ")"
pdb.set_trace()
return optionset
the html generated for the select is below.
<select id="id_size_option" name="size_option" choices="(('Small', 'Small')('Medium', 'Medium')('Large', 'Large'))">
so the problem is probably the optionset passed back. i can guess as much. i just don't know whats wrong with it. i cant find documentation that shows how this should be formatted inside the select.
| [
"What is this supposed to be doing? The format for a list of choices is a standard tuple:\nCHOICES = (\n ('x', 'choice x'),\n ('y', 'choice y'),\n)\n\nso I don't understand what you are trying to do with all that string formatting.\nSecondly, choices is not an element of the widget's attrs, it is an attribute... | [
1
] | [] | [] | [
"django_forms",
"django_models",
"django_views",
"python"
] | stackoverflow_0004203347_django_forms_django_models_django_views_python.txt |
Q:
How to manage different distribution packages of the same Python package?
Is there a way (with distribute or another package) to manage different distributions (meaning different setup.py files) of the same Python package?
A:
You might have a look to buildout. With buildout you can have a single setup.py for a package and have multiple buildout configuration files that specify different ways of building that package with the other packages you want to have in the same distribution (including its version dependencies).
I think with pip freeze, pip bundle you can also achieve something similar but AFAIK only for versions of packages (you can't install and setup an LDAP server for example, but you can do it that in buildout).
| How to manage different distribution packages of the same Python package? | Is there a way (with distribute or another package) to manage different distributions (meaning different setup.py files) of the same Python package?
| [
"You might have a look to buildout. With buildout you can have a single setup.py for a package and have multiple buildout configuration files that specify different ways of building that package with the other packages you want to have in the same distribution (including its version dependencies).\nI think with pip... | [
1
] | [] | [] | [
"distribution",
"packaging",
"python"
] | stackoverflow_0004204144_distribution_packaging_python.txt |
Q:
assignment in python
I know that "variable assignment" in python is in fact a binding / re-bindign of a name (the variable) to an object.
This brings the question: is it possible to have proper assignment in python, eg make an object equal to another object?
I guess there is no need for that in python:
Inmutable objects cannot be 'assigned to' since they can't be changed
Mutable objects could potentially be assigned to, since they can change, and this could be useful, since you may want to manipulate a copy of dictionary separately from the original one. However, in these cases the python philosophy is to offer a cloning method on the mutable object, so you can bind a copy rather than the original.
So I guess the answer is that there is no assignment in python, the best way to mimic it would be binding to a cloned object
I simply wanted to share the question in case I'm missing something important here
Thanks
EDIT:
Both Lie Ryan and Sven Marnach answers are good, I guess the overall answer is a mix of both:
For user defined types, use the idiom:
a.dict = dict(b.dict)
(I guess this has problems as well if the assigned class has redefined attribute access methods, but lets not be fussy :))
For mutable built-ins (lists and dicts) use the cloning / copying methods they provide (eg slices, update)
finally inmutable built-ins can't be changed so can't be assigned
I'll choose Lie Ryan because it's an elegant idiom that I hadn't thought of.
Thanks!
A:
I think you are right with your characterization of assignment in Python -- I just would like to add a different method of cloning and ways of assignment in special cases.
"Copy-constructing" a mutable built-in Python object will yield a (shallow) copy of that object:
l = [2, 3]
m = list(l)
l is m
--> False
[Edit: As pointed out by Paul McGuire in the comments, the behaviour of a "copy contructor" (forgive me the C++ terminology) for a immutable built-in Python object is implementation dependent -- you might get a copy or just the same object. But because the object is immutable anyway, you shouldn't care.]
The copy constructor could be called generically by y = type(x)(x), but this seems a bit cryptic. And of course, there is the copy module which allows for shallow and deep copies.
Some Python objects allow assignment. For example, you can assign to a list without creating a new object:
l = [2, 3]
m = l
l[:] = [3, 4, 5]
m
--> [3, 4, 5]
For dictionaries, you could use the clear() method followed by update(otherdict) to assign to a dictionary without creating a new object. For a set s, you can use
s.clear()
s |= otherset
A:
This brings the question: is it
possible to have proper assignment in
python, eg make an object equal to
another object?
Yes you can:
a.__dict__ = dict(b.__dict__)
will do the default assignment semantic in C/C++ (i.e. do a shallow assignment).
The problem with such generalized assignment is that it never works for everybody. In C++, you can override the assignment operator since you always have to pick whether you want a fully shallow assignment, fully deep assignment, or any shade between fully deep copy and fully shallow copy.
A:
I don't think you are missing anything.
I like to picture variables in python as the name written on 'labels' that are attached to boxes but can change its placement by assignment, whereas in other languages, assignment changes the box's contents (and the assignment operator can be overloaded).
Beginners can write quite complex applications without being aware of that, but they are usually messy programs.
| assignment in python | I know that "variable assignment" in python is in fact a binding / re-bindign of a name (the variable) to an object.
This brings the question: is it possible to have proper assignment in python, eg make an object equal to another object?
I guess there is no need for that in python:
Inmutable objects cannot be 'assigned to' since they can't be changed
Mutable objects could potentially be assigned to, since they can change, and this could be useful, since you may want to manipulate a copy of dictionary separately from the original one. However, in these cases the python philosophy is to offer a cloning method on the mutable object, so you can bind a copy rather than the original.
So I guess the answer is that there is no assignment in python, the best way to mimic it would be binding to a cloned object
I simply wanted to share the question in case I'm missing something important here
Thanks
EDIT:
Both Lie Ryan and Sven Marnach answers are good, I guess the overall answer is a mix of both:
For user defined types, use the idiom:
a.dict = dict(b.dict)
(I guess this has problems as well if the assigned class has redefined attribute access methods, but lets not be fussy :))
For mutable built-ins (lists and dicts) use the cloning / copying methods they provide (eg slices, update)
finally inmutable built-ins can't be changed so can't be assigned
I'll choose Lie Ryan because it's an elegant idiom that I hadn't thought of.
Thanks!
| [
"I think you are right with your characterization of assignment in Python -- I just would like to add a different method of cloning and ways of assignment in special cases.\n\"Copy-constructing\" a mutable built-in Python object will yield a (shallow) copy of that object:\nl = [2, 3]\nm = list(l)\nl is m\n--> False... | [
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004204075_python.txt |
Q:
Real-time SQLite and PostgreSQL bi-directional synchronization using python
Is there any python library that can keep a client-side SQLite database in sync with a server-side PostgreSQL database?
There are solutions for Java, such as Daffodil or SymmetricDS. Is there something similar for python?
A:
SymmetricDS is a server-side solution for synchronization that gets triggered regardless of which language is being used to access the database. You should still be able to use that to synchronize the databases, while using Python libraries to actually query them. I would recommend sqlalchemy as a good database-independent query layer for Python.
| Real-time SQLite and PostgreSQL bi-directional synchronization using python | Is there any python library that can keep a client-side SQLite database in sync with a server-side PostgreSQL database?
There are solutions for Java, such as Daffodil or SymmetricDS. Is there something similar for python?
| [
"SymmetricDS is a server-side solution for synchronization that gets triggered regardless of which language is being used to access the database. You should still be able to use that to synchronize the databases, while using Python libraries to actually query them. I would recommend sqlalchemy as a good database-in... | [
1
] | [] | [] | [
"database",
"python",
"synchronization"
] | stackoverflow_0002693002_database_python_synchronization.txt |
Q:
How to refresh/replace gtk.ToolItemGroup
I wrote this code, it's supposed to be a clipart browser (locked to "klip" folder under current directory).
When I start add signal at folder button (dbutton) I screw up: I don't know how to refresh the toolitemgroup content and icons keep appended, I can't remove manually since the button generated in loop.
And one more, how can I "auto-fit/trim" the button label? Cause it grows insane if the filename is lengthy.
import gtk
from os.path import join,normpath,splitext, isdir
from os import getcwd, walk, mkdir
klip="klip"
klipdir=join(getcwd(),klip)
#init dir
if not isdir(klipdir):
mkdir(klipdir)
class kaosmu:
def icon_builder_cb(self, widget, data=klip):
if data != klip:
homebutton = gtk.ToolButton(gtk.STOCK_HOME)
browser.add(homebutton)
upbutton = gtk.ToolButton(gtk.STOCK_GO_UP)
browser.add(upbutton)
#folder
idx=dirs.index(data)
print idx
for i in dirs[idx+1]:
dbutton = gtk.ToolButton(gtk.STOCK_OPEN)
dbutton.set_label(i)
dbutton.connect("clicked", self.icon_builder_cb, join(data,i))
browser.add(dbutton)
#files
for i in dirs[idx+2]:
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(join(data,i),32,32)
img=gtk.Image()
img.set_from_pixbuf(pixbuf)
svg = gtk.ToolButton(img,splitext(i)[0])
browser.add(svg)
browser.show_all()
def im_browser_cb(self, widget, data=klipdir):
global dirs
dirs = []
for (p, d, f) in walk(data):
key=p[len(data)-len(klip):]
dirs.append(key)
dirs.append(d)
dirs.append(f)
def __init__(self):
self.im_browser_cb(None)
window = gtk.Window()
window.set_default_size(1024, 800)
window.set_border_width(2)
window.connect("destroy", lambda w: gtk.main_quit())
drawingarea = gtk.DrawingArea()
drawingarea.set_size_request(600, 700)
hpane = gtk.HPaned()
menuscroll = gtk.ScrolledWindow()
canvasscroll = gtk.ScrolledWindow()
toolpalette = gtk.ToolPalette()
toolpalette.set_style(gtk.TOOLBAR_BOTH)
toolpalette.set_icon_size(gtk.ICON_SIZE_DND)
hpane.set_position(250)
window.add(hpane)
hpane.add1(menuscroll)
hpane.add2(canvasscroll)
menuscroll.add_with_viewport(toolpalette)
canvasscroll.add_with_viewport(drawingarea)
global browser
browser = gtk.ToolItemGroup(" Browser ")
toolpalette.add(browser)
toolpalette.set_expand(browser, True)
self.icon_builder_cb(None)
window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
kaos = kaosmu()
kaos.main()
A:
I solved this with:
while browser.get_nth_item(0):
browser.remove(browser.get_nth_item(0))
| How to refresh/replace gtk.ToolItemGroup | I wrote this code, it's supposed to be a clipart browser (locked to "klip" folder under current directory).
When I start add signal at folder button (dbutton) I screw up: I don't know how to refresh the toolitemgroup content and icons keep appended, I can't remove manually since the button generated in loop.
And one more, how can I "auto-fit/trim" the button label? Cause it grows insane if the filename is lengthy.
import gtk
from os.path import join,normpath,splitext, isdir
from os import getcwd, walk, mkdir
klip="klip"
klipdir=join(getcwd(),klip)
#init dir
if not isdir(klipdir):
mkdir(klipdir)
class kaosmu:
def icon_builder_cb(self, widget, data=klip):
if data != klip:
homebutton = gtk.ToolButton(gtk.STOCK_HOME)
browser.add(homebutton)
upbutton = gtk.ToolButton(gtk.STOCK_GO_UP)
browser.add(upbutton)
#folder
idx=dirs.index(data)
print idx
for i in dirs[idx+1]:
dbutton = gtk.ToolButton(gtk.STOCK_OPEN)
dbutton.set_label(i)
dbutton.connect("clicked", self.icon_builder_cb, join(data,i))
browser.add(dbutton)
#files
for i in dirs[idx+2]:
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(join(data,i),32,32)
img=gtk.Image()
img.set_from_pixbuf(pixbuf)
svg = gtk.ToolButton(img,splitext(i)[0])
browser.add(svg)
browser.show_all()
def im_browser_cb(self, widget, data=klipdir):
global dirs
dirs = []
for (p, d, f) in walk(data):
key=p[len(data)-len(klip):]
dirs.append(key)
dirs.append(d)
dirs.append(f)
def __init__(self):
self.im_browser_cb(None)
window = gtk.Window()
window.set_default_size(1024, 800)
window.set_border_width(2)
window.connect("destroy", lambda w: gtk.main_quit())
drawingarea = gtk.DrawingArea()
drawingarea.set_size_request(600, 700)
hpane = gtk.HPaned()
menuscroll = gtk.ScrolledWindow()
canvasscroll = gtk.ScrolledWindow()
toolpalette = gtk.ToolPalette()
toolpalette.set_style(gtk.TOOLBAR_BOTH)
toolpalette.set_icon_size(gtk.ICON_SIZE_DND)
hpane.set_position(250)
window.add(hpane)
hpane.add1(menuscroll)
hpane.add2(canvasscroll)
menuscroll.add_with_viewport(toolpalette)
canvasscroll.add_with_viewport(drawingarea)
global browser
browser = gtk.ToolItemGroup(" Browser ")
toolpalette.add(browser)
toolpalette.set_expand(browser, True)
self.icon_builder_cb(None)
window.show_all()
def main(self):
gtk.main()
if __name__ == "__main__":
kaos = kaosmu()
kaos.main()
| [
"I solved this with:\nwhile browser.get_nth_item(0):\n browser.remove(browser.get_nth_item(0))\n\n"
] | [
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004202919_gtk_pygtk_python.txt |
Q:
Overriding admin view methods - Django
I need to override the an add form within the admin panel.
I'm thinking of accomplishing this by writing a view which would then point to the admin view for the final result.
Something similar to this (where admin_basic_ass_user_view is the admin view)
@required_login
def add_user(request):
if condition:
return admin_basic_add_user_view(request)
return render_to_response("admin/auth/user/add_form.html", { ... })
Any ideas?
A:
Why not just override the relevant methods with your ModelAdmin subclass? That's why it's a class, after all.
A:
Add something like this to your urls.py
((r'^admin/auth/users/add/$', 'Project.SomeAPP.admin_views.add_user'),
The path needs to point to your new view. You should see the results of your new view in the admin interface's add user page.
EDIT: I forgot to mention, make sure you add that line BEFORE the normal admin interface line in the urls.py
| Overriding admin view methods - Django | I need to override the an add form within the admin panel.
I'm thinking of accomplishing this by writing a view which would then point to the admin view for the final result.
Something similar to this (where admin_basic_ass_user_view is the admin view)
@required_login
def add_user(request):
if condition:
return admin_basic_add_user_view(request)
return render_to_response("admin/auth/user/add_form.html", { ... })
Any ideas?
| [
"Why not just override the relevant methods with your ModelAdmin subclass? That's why it's a class, after all.\n",
"Add something like this to your urls.py\n((r'^admin/auth/users/add/$', 'Project.SomeAPP.admin_views.add_user'),\n\nThe path needs to point to your new view. You should see the results of your new vi... | [
3,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004204504_django_django_admin_python.txt |
Q:
Locate "N Gram" substrings that are smallest distance away from a target string N character long
I am looking for an algorithm, preferably in Python that would help me locate substrings, N characters long, of exisiting strings that are closest to a target string N character long.
Consider the target string, that is, say, 4 characters long, to be:
targetString -> '1111'
Assume this is the string I have available with me ( I will generate substrings of this for "best alignment" matching ):
nonEmptySubStrings -> ['110101']
Substrings of the above that are 4 characters long:
nGramsSubStrings -> ['0101', '1010', '1101']
I want to write/use a "Magic Function" that would select the string closest to targetString :
someMagicFunction -> ['1101']
Some more examples:
nonEmptySubStrings -> ['101011']
nGramsSubStrings -> ['0101', '1010', '1011']
someMagicFunction -> ['1011']
nonEmptySubStrings -> ['10101']
nGramsSubStrings -> ['0101', '1010']
someMagicFunction -> ['0101', '1010']
Is this "Magic Function" a well known substring problem?
I really want to find the min. number of changes in nonEmptySubStrings so that it would have targetString as a substring.
A:
I believe you need Edit Distance. Peter Norvig's spelling corrector is an implementation example in python. Here's an implementation of Levenshtein Distance.
See also this question.
EDIT:
This is fairly frequent in bioinformatics. See e.g. FASTA and BLAST. Bioinformatics has many flavors of this algorithm. See Sequence Alignment for a survey of methods.
A:
As part of a discussion a while ago on gene matching, I wrote this pyparsing example, implementing a pyparsing class CloseMatch. Normally pyparsing expressions return a structure containing matched strings and any named results, but CloseMatch returns a 2-tuple containing the matching string and a list of mismatch locations within the matched string. Here is how CloseMatch would be used:
searchseq = CloseMatch("TTAAATCTAGAAGAT", 3)
for g in genedata:
print "%s (%d)" % (g.id, g.genelen)
print "-"*24
for t,startLoc,endLoc in searchseq.scanString(g.gene):
matched, mismatches = t[0]
print "MATCH:", searchseq.sequence
print "FOUND:", matched
if mismatches:
print " ", ''.join(' ' if i not in mismatches else '*'
for i,c in enumerate(searchseq.sequence))
else:
print "<exact match>"
print "at location", startLoc
Here is a sample output of a partial match:
organism=Toxoplasma_gondii_RH (258)
------------------------
MATCH: TTAAATCTAGAAGAT
FOUND: TTAAATTTAGGAGCT
* * *
at location 195
Note that this class does not find overlapping matches. That can still be accomplished, but with a slightly different approach with scanString (which I will include in the next pyparsing release).
A:
Base on OP's comment to question, this is what is desired
import functools
def edit_distance(str1, str2):
#implement it here
f = functools.operator(edit_distance, target_string)
return min(f(s) for s in slices(string_)) # use slices from below
This will return the minimum edit distance of any substring to the target string. It will not indicate which string that is or what its index is. It could be easily modified to do
so though.
The naive way, which can be the best way, is
import functools
def diff(str1, str2):
# However you test the distance gets defined here. e.g. Hamming distance,
# Levenshtein distance, etc.
def slices(string_, L):
for i in xrange(len(string_) - L + 1)):
yield string_[i:i+L]
best_match = min(slices(string_), key=functools.partial(diff, target_string))
This wont return the index at which the substring occurs though. Of course you didn't specify that you need it in your question ;)
If you want to get better than this, it will depend on how you're measuring the distance and will basically boil down to avoiding checking some substrings by infering that you would have to change at least x chars to get a better match than you already have. At that point, you might as well just change x chars by jumping ahead x chars.
| Locate "N Gram" substrings that are smallest distance away from a target string N character long | I am looking for an algorithm, preferably in Python that would help me locate substrings, N characters long, of exisiting strings that are closest to a target string N character long.
Consider the target string, that is, say, 4 characters long, to be:
targetString -> '1111'
Assume this is the string I have available with me ( I will generate substrings of this for "best alignment" matching ):
nonEmptySubStrings -> ['110101']
Substrings of the above that are 4 characters long:
nGramsSubStrings -> ['0101', '1010', '1101']
I want to write/use a "Magic Function" that would select the string closest to targetString :
someMagicFunction -> ['1101']
Some more examples:
nonEmptySubStrings -> ['101011']
nGramsSubStrings -> ['0101', '1010', '1011']
someMagicFunction -> ['1011']
nonEmptySubStrings -> ['10101']
nGramsSubStrings -> ['0101', '1010']
someMagicFunction -> ['0101', '1010']
Is this "Magic Function" a well known substring problem?
I really want to find the min. number of changes in nonEmptySubStrings so that it would have targetString as a substring.
| [
"I believe you need Edit Distance. Peter Norvig's spelling corrector is an implementation example in python. Here's an implementation of Levenshtein Distance.\nSee also this question.\nEDIT:\nThis is fairly frequent in bioinformatics. See e.g. FASTA and BLAST. Bioinformatics has many flavors of this algorithm. See ... | [
3,
2,
1
] | [] | [] | [
"python",
"string",
"string_matching",
"substring"
] | stackoverflow_0004203142_python_string_string_matching_substring.txt |
Q:
Instant messenger streaming with libVLC python wrapper
I'm trying to develop an instant messenger client that supports video streaming. I am working with the libVLC wrapper for Python. Most basic functions of an IM client are already there, my problem comes with the video streaming. I've been able to do basic tests like streaming a video and playing it in a tkinter form with my own code. But when it comes to streaming to many users, and recieving many streams from other users I'm completely lost. I'd appreciate any help you can give me, maybe this is not the right way to do it and you can point me out the direction I should take, everything helps as I am not a very experienced programmer. Thanks in advance.
A:
I don't think it will be easy.
http://wiki.videolan.org/VideoLan_VideoConference#See_also might give you some clues as to directions to try...
| Instant messenger streaming with libVLC python wrapper | I'm trying to develop an instant messenger client that supports video streaming. I am working with the libVLC wrapper for Python. Most basic functions of an IM client are already there, my problem comes with the video streaming. I've been able to do basic tests like streaming a video and playing it in a tkinter form with my own code. But when it comes to streaming to many users, and recieving many streams from other users I'm completely lost. I'd appreciate any help you can give me, maybe this is not the right way to do it and you can point me out the direction I should take, everything helps as I am not a very experienced programmer. Thanks in advance.
| [
"I don't think it will be easy.\nhttp://wiki.videolan.org/VideoLan_VideoConference#See_also might give you some clues as to directions to try...\n"
] | [
0
] | [] | [] | [
"instant_messaging",
"libvlc",
"python",
"streaming",
"vlc"
] | stackoverflow_0003824296_instant_messaging_libvlc_python_streaming_vlc.txt |
Q:
Python logging IndexError: list index out of range
I have an application the sets up the logging using:
logging.basicConfig(level=logging_level, format=format_string, filename=log_file, filemode='a')
then call
logging.debug("My Message")
etc. to log messeages. This work fine in most of my application, but then for a particular module I get this error
File "C:\path\to\my\module\MyModule.py", line 53, in __init__
logging.debug("__init__ called")
File "C:\Python26\Lib\logging\__init__.py", line 1481, in debug
root.debug(*((msg,)+args), **kwargs)
File "C:\Python26\Lib\logging\__init__.py", line 1035, in debug
if self.isEnabledFor(DEBUG):
File "C:\Python26\Lib\logging\__init__.py", line 1242, in isEnabledFor
return level >= self.getEffectiveLevel()
File "C:\Python26\Lib\logging\__init__.py", line 1230, in getEffectiveLevel
while logger:
IndexError: list index out of range
Does anyone have any ideas on what could be causing this? Or where else to look to read up on it. I have already read through the logging module code and the python reference pages
A:
Doug Helmann's site has some guidance on using Python's logging module.
There are also some examples to be downloaded there, which I haven't tried.
A:
Something seems very wrong with your installation - it's hard to see how a line like
while logger:
would generate an IndexError.
So, delete all .pyc and .pyo files from your system (including in the stdlib folders) and try again. Ensure that none of your modules have the same name as any modules in the standard library.
Also, what version of Python are you using, and on which platform?
Update: If you are using embedded in a C++ program, or with C extensions, it's quite possible that some C or C++ code is clobbering memory, leading to the IndexError in a most unexpected place.
Can you reproduce in a pure-Python environment? If not, I fear the problem might be in the C/C++ code. It's also easier to clobber stuff in multi-threaded environments :-(
| Python logging IndexError: list index out of range | I have an application the sets up the logging using:
logging.basicConfig(level=logging_level, format=format_string, filename=log_file, filemode='a')
then call
logging.debug("My Message")
etc. to log messeages. This work fine in most of my application, but then for a particular module I get this error
File "C:\path\to\my\module\MyModule.py", line 53, in __init__
logging.debug("__init__ called")
File "C:\Python26\Lib\logging\__init__.py", line 1481, in debug
root.debug(*((msg,)+args), **kwargs)
File "C:\Python26\Lib\logging\__init__.py", line 1035, in debug
if self.isEnabledFor(DEBUG):
File "C:\Python26\Lib\logging\__init__.py", line 1242, in isEnabledFor
return level >= self.getEffectiveLevel()
File "C:\Python26\Lib\logging\__init__.py", line 1230, in getEffectiveLevel
while logger:
IndexError: list index out of range
Does anyone have any ideas on what could be causing this? Or where else to look to read up on it. I have already read through the logging module code and the python reference pages
| [
"Doug Helmann's site has some guidance on using Python's logging module.\nThere are also some examples to be downloaded there, which I haven't tried.\n",
"Something seems very wrong with your installation - it's hard to see how a line like\nwhile logger:\n\nwould generate an IndexError.\nSo, delete all .pyc and .... | [
0,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0004204764_logging_python.txt |
Q:
cgi scripts with no server
My goal is to use to make it easy for non-programmers to execute a Python script with fairly complex options, on a single local machine that I have access to. I'd like to use the browser (specifically Safari on OS X) as a poor man's GUI. A short script would process the form data and then send it on to the main program(s).
I have some basic examples of python scripts run using the built-in Apache server, by clicking submit on a form whose html is th:
e.g. here. What I want to do now is do it without the server, just getting the form to invoke the script in the same directory. Do I have to learn javascript or ...? I'd be grateful for any leads you have. Thanks.
A:
Well, there always has to be some kind of "server" involved to communicate over HTTP. You could have a python script listening on port 80 on your machine, that in turn runs the scripts specified with the form's action attribute.
You won't get away without some sort of server, I'm afraid.
PS: There are already a couple of good minimalistic python HTTP servers that would do the trick. Just google for it.
Regards, aefxx
A:
Pyjamas Desktop will allow you to deploy a browser-based desktop application.
A:
It doesn't make sense -- what a browser does when it submits a form by definition is to make a request to a web server.
If all that's going on is that you don't want to be running Apache, you could hook something simple up using the CGIHTTPServer class that's provided as part of the Python Standard library.
If you don't want a server process at all, and you're using a suitably modern browser, you may want to look at using HTML5 local storage, but that's not a Python solution.
| cgi scripts with no server | My goal is to use to make it easy for non-programmers to execute a Python script with fairly complex options, on a single local machine that I have access to. I'd like to use the browser (specifically Safari on OS X) as a poor man's GUI. A short script would process the form data and then send it on to the main program(s).
I have some basic examples of python scripts run using the built-in Apache server, by clicking submit on a form whose html is th:
e.g. here. What I want to do now is do it without the server, just getting the form to invoke the script in the same directory. Do I have to learn javascript or ...? I'd be grateful for any leads you have. Thanks.
| [
"Well, there always has to be some kind of \"server\" involved to communicate over HTTP. You could have a python script listening on port 80 on your machine, that in turn runs the scripts specified with the form's action attribute.\nYou won't get away without some sort of server, I'm afraid.\nPS: There are already ... | [
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004205697_python.txt |
Q:
How to properly encode image URL with equal sign for Facebook open graph tag
I have a page with an Open Graph image tag:
<meta property="og:image" content="http://childhumor2.homeip.net:9009/_ah/img/RYCF7Ty7wODp9R-N_QIWYA===s200"/>
The image is a GAE blob and the URL comes from calling get_serving_url. The URL works fine normally.
Now, if someone likes this page, the thumbnail image that is shown in the newsfeed is broken. Only a blank 1x1 image is returned to the browser.
Inspecting the FB page, the generated HTML is:
<img src="http://external.ak.fbcdn.net/safe_image.php?d=6b635a7f80252e93c6b28e2dbe4ad440&w=90&h=90&url=http%3A%2F%2Fchildhumor2.homeip.net%3A9009%2F_ah%2Fimg%2FRYCF7Ty7wODp9R-N_QIWYA%3D%3D%3Ds200" class="img">
When viewing the liking user's news feed for the first time, I see FB hit my server for the image:
INFO 2010-11-14 21:33:17,701 dev_appserver.py:3283] "GET /_ah/img/RYCF7Ty7wODp9R-N_QIWYA%3D%3D%3Ds200 HTTP/1.1" 500 -
It is obvious that there is a URL encoding problem with the equal signs in the URL but I have no idea who is at fault here.
Should FB be unescaping %3D before calling back to my server for the image?
Is GAE not properly handling an encoded URL?
Should I be encoding the URL in the Open Graph tag somehow? (I tried urllib.quote-ing it with the same results.)
To make things more confusing, the Facebook URL Linter retrieves the image properly. Also if doing a FB share on the page, the thumbnail preview will be shown correctly. This leads me to believe this is a bug with the safe_image.php script FB is proxying/caching the image with.
A:
It is probably the case that Facebook should be unquoting the value so that it matches the original og:image you listed, and you should write a bug for that (as Nathan suggested).
However, technically speaking %3D and = have the same meaning in the path section of a URL and should be treated equally so that might also be bug worthy on the GAE side of things. In this case you probably want to urllib.unquote() the path when handled on GAE. (perhaps you could simply redirect to the unescaped version)
A:
If the URL linter says everything is working correctly, then you are most likely correct that it is a bug with Facebook. I would recommend searching through their existing bugs to see if you can find one that exists, and if not post a new bug. There are currently about 4,300 platform bugs open so it is certainly not unheard of that something is broken. Facebook Bugs: http://bugs.developers.facebook.net/
A:
As a workaround, don't use the Google Image Serving Service. Instead write a handler to retrieve the blob from the datastore, transform it, and stream it back to the client. This allows you to construct a simpler URL that will not be munged by Facebook.
Example from GAE Docs:
class Thumbnailer(webapp.RequestHandler):
def get(self):
blob_key = self.request.get("blob_key")
if blob_key:
blob_info = blobstore.get(blob_key)
if blob_info:
img = images.Image(blob_key=blob_key)
img.resize(width=80, height=100)
img.im_feeling_lucky()
thumbnail = img.execute_transforms(output_encoding=images.JPEG)
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(thumbnail)
return
# Either "blob_key" wasn't provided, or there was no value with that ID
# in the Blobstore.
self.error(404)
| How to properly encode image URL with equal sign for Facebook open graph tag | I have a page with an Open Graph image tag:
<meta property="og:image" content="http://childhumor2.homeip.net:9009/_ah/img/RYCF7Ty7wODp9R-N_QIWYA===s200"/>
The image is a GAE blob and the URL comes from calling get_serving_url. The URL works fine normally.
Now, if someone likes this page, the thumbnail image that is shown in the newsfeed is broken. Only a blank 1x1 image is returned to the browser.
Inspecting the FB page, the generated HTML is:
<img src="http://external.ak.fbcdn.net/safe_image.php?d=6b635a7f80252e93c6b28e2dbe4ad440&w=90&h=90&url=http%3A%2F%2Fchildhumor2.homeip.net%3A9009%2F_ah%2Fimg%2FRYCF7Ty7wODp9R-N_QIWYA%3D%3D%3Ds200" class="img">
When viewing the liking user's news feed for the first time, I see FB hit my server for the image:
INFO 2010-11-14 21:33:17,701 dev_appserver.py:3283] "GET /_ah/img/RYCF7Ty7wODp9R-N_QIWYA%3D%3D%3Ds200 HTTP/1.1" 500 -
It is obvious that there is a URL encoding problem with the equal signs in the URL but I have no idea who is at fault here.
Should FB be unescaping %3D before calling back to my server for the image?
Is GAE not properly handling an encoded URL?
Should I be encoding the URL in the Open Graph tag somehow? (I tried urllib.quote-ing it with the same results.)
To make things more confusing, the Facebook URL Linter retrieves the image properly. Also if doing a FB share on the page, the thumbnail preview will be shown correctly. This leads me to believe this is a bug with the safe_image.php script FB is proxying/caching the image with.
| [
"It is probably the case that Facebook should be unquoting the value so that it matches the original og:image you listed, and you should write a bug for that (as Nathan suggested).\nHowever, technically speaking %3D and = have the same meaning in the path section of a URL and should be treated equally so that might... | [
3,
1,
0
] | [] | [] | [
"facebook",
"google_app_engine",
"python"
] | stackoverflow_0004179906_facebook_google_app_engine_python.txt |
Q:
How to force a ndarray show in normal way instead of scientific notation?
I'm trying to print a ndarray on the screen. But python always shows it in scientific notation, which I don't like. For a scalar we can use
>>> print '%2.4f' %(7.47212470e-01)
0.7472
But how to do that for a numpy.ndarray like this :
[[ 7.47212470e-01 3.71730070e-01 1.16736538e-01 1.22172891e-02]
[ 2.79279640e+00 1.31147152e+00 7.43946656e-02 3.08162255e-02]
[ 6.93657970e+00 3.14008688e+00 1.02851599e-01 3.96611266e-02]
[ 8.49295040e+00 3.94730094e+00 8.99398479e-02 7.60969188e-02]
[ 2.01849250e+01 8.62584092e+00 8.75722302e-02 6.17109672e-02]
[ 2.22570710e+01 1.00291292e+01 1.20918359e-01 1.07250131e-01]
[ 2.82496660e+01 1.27882133e+01 1.08438172e-01 1.58723714e-01]
[ 5.89170270e+01 2.55268510e+01 1.31990966e-01 1.61599514e-01]]
The method .astype(float) does not change the result, and .round(4) returns:
[[ 7.47200000e-01 3.71700000e-01 1.16700000e-01 1.22000000e-02]
[ 2.79280000e+00 1.31150000e+00 7.44000000e-02 3.08000000e-02]
[ 6.93660000e+00 3.14010000e+00 1.02900000e-01 3.97000000e-02]
[ 8.49300000e+00 3.94730000e+00 8.99000000e-02 7.61000000e-02]
[ 2.01849000e+01 8.62580000e+00 8.76000000e-02 6.17000000e-02]
[ 2.22571000e+01 1.00291000e+01 1.20900000e-01 1.07300000e-01]
[ 2.82497000e+01 1.27882000e+01 1.08400000e-01 1.58700000e-01]
[ 5.89170000e+01 2.55269000e+01 1.32000000e-01 1.61600000e-01]]
I just simply want the 0.7472 0.3717 etc.
A:
The numpy.set_string_function function can be used to change the string representation of arrays.
You can also use numpy.set_print_options to change the precision used by default and turn off reporting of small numbers in scientific notation.
From the examples for set_print_options:
>>> np.set_printoptions(precision=4)
>>> print np.array([1.123456789])
[ 1.1235]
A:
I don't know about the numpy arrays but I was simply facing the same problem while doing a project in Python.
Take a look at the Decimal class provided http://docs.python.org/library/decimal.html .
I don't know if it's provided in numpy though.
| How to force a ndarray show in normal way instead of scientific notation? | I'm trying to print a ndarray on the screen. But python always shows it in scientific notation, which I don't like. For a scalar we can use
>>> print '%2.4f' %(7.47212470e-01)
0.7472
But how to do that for a numpy.ndarray like this :
[[ 7.47212470e-01 3.71730070e-01 1.16736538e-01 1.22172891e-02]
[ 2.79279640e+00 1.31147152e+00 7.43946656e-02 3.08162255e-02]
[ 6.93657970e+00 3.14008688e+00 1.02851599e-01 3.96611266e-02]
[ 8.49295040e+00 3.94730094e+00 8.99398479e-02 7.60969188e-02]
[ 2.01849250e+01 8.62584092e+00 8.75722302e-02 6.17109672e-02]
[ 2.22570710e+01 1.00291292e+01 1.20918359e-01 1.07250131e-01]
[ 2.82496660e+01 1.27882133e+01 1.08438172e-01 1.58723714e-01]
[ 5.89170270e+01 2.55268510e+01 1.31990966e-01 1.61599514e-01]]
The method .astype(float) does not change the result, and .round(4) returns:
[[ 7.47200000e-01 3.71700000e-01 1.16700000e-01 1.22000000e-02]
[ 2.79280000e+00 1.31150000e+00 7.44000000e-02 3.08000000e-02]
[ 6.93660000e+00 3.14010000e+00 1.02900000e-01 3.97000000e-02]
[ 8.49300000e+00 3.94730000e+00 8.99000000e-02 7.61000000e-02]
[ 2.01849000e+01 8.62580000e+00 8.76000000e-02 6.17000000e-02]
[ 2.22571000e+01 1.00291000e+01 1.20900000e-01 1.07300000e-01]
[ 2.82497000e+01 1.27882000e+01 1.08400000e-01 1.58700000e-01]
[ 5.89170000e+01 2.55269000e+01 1.32000000e-01 1.61600000e-01]]
I just simply want the 0.7472 0.3717 etc.
| [
"The numpy.set_string_function function can be used to change the string representation of arrays.\nYou can also use numpy.set_print_options to change the precision used by default and turn off reporting of small numbers in scientific notation.\nFrom the examples for set_print_options:\n>>> np.set_printoptions(prec... | [
10,
0
] | [] | [] | [
"arrays",
"matrix",
"numpy",
"python",
"scientific_notation"
] | stackoverflow_0004205259_arrays_matrix_numpy_python_scientific_notation.txt |
Q:
How do you extend Django's sitemap module to create more complex sitemaps?
I have a supplier that wants a sitemap that contains much more meta data than what you would see in a normal search engine sitemap. As a result I would like find a tidy way of extending django's sitemap module. Has anyone done this? Or could you provide this django Noob with the code to do it?
Mike
A:
If you really wanted to do this you would need to extend django.contrib.sitemaps.Sitemap.get_urls to add the additional meta information to the url_info dictionary. The current get_urls is given below from django.contrib.sitemaps:
def get_urls(self, page=1, site=None):
if site is None:
if Site._meta.installed:
try:
site = Site.objects.get_current()
except Site.DoesNotExist:
pass
if site is None:
raise ImproperlyConfigured("In order to use Sitemaps you must either use the sites framework or pass in a Site or RequestSite object in your view code.")
urls = []
for item in self.paginator.page(page).object_list:
loc = "http://%s%s" % (site.domain, self.__get('location', item))
priority = self.__get('priority', item, None)
url_info = {
'location': loc,
'lastmod': self.__get('lastmod', item, None),
'changefreq': self.__get('changefreq', item, None),
'priority': str(priority is not None and priority or '')
}
urls.append(url_info)
return urls
After that you would need to change django/contrib/sitemaps/templates/sitemap.xml to include your extra information in the sitemap. Unrelated to Django if you are adding extra meta information you should read up on the sitemaps.org protocol section regarding extending the protocol.
| How do you extend Django's sitemap module to create more complex sitemaps? | I have a supplier that wants a sitemap that contains much more meta data than what you would see in a normal search engine sitemap. As a result I would like find a tidy way of extending django's sitemap module. Has anyone done this? Or could you provide this django Noob with the code to do it?
Mike
| [
"If you really wanted to do this you would need to extend django.contrib.sitemaps.Sitemap.get_urls to add the additional meta information to the url_info dictionary. The current get_urls is given below from django.contrib.sitemaps:\ndef get_urls(self, page=1, site=None):\n if site is None:\n if Site._meta... | [
2
] | [] | [] | [
"django",
"python",
"sitemap"
] | stackoverflow_0004204211_django_python_sitemap.txt |
Q:
Launch python into a mac application
I have a software written in python with a graphical user interface written in PyQt.
To create an executable of the software I ship with it a Python and a Qt precompiled version and the trick seems to work in windows and linux since I know How to create an istaller.
The problem is to embed evrything into a mac .app
To launch the software I use the following shel script
export DYLD_LIBRARY_PATH=`pwd`/lib:$DYLD_LIBRARY_PATH
export DYLD_FRAMEWORK_PATH=`pwd`/Resources
PYTHONPATH=$PYTHONPATH:. bin/python ProgramPy/Main.py
If I run this shell script from outside it works fine but when I try to embed everything into an app with platypus I get the following error.
dyld: Library not loaded: @executable_path/../.Python
Referenced from: /Users/luca/Desktop/TempScript.app/Contents/Resources/bin/python
Reason: image not found
./run.sh: line 3: 725 Trace/BPT trap PYTHONPATH=$PYTHONPATH:. bin/python ProgramPy/Main.py
Note that the file /Users/luca/Desktop/TempScript.app/Contents/Resources/bin/python
is the executable version of python and it is actually located into the Resources folder of the app. I don't understand why the system cannot find it...
Maybe I miss something in understanding how mac uses the pythonpath ...
Thanks
A:
I just use py2app.
| Launch python into a mac application | I have a software written in python with a graphical user interface written in PyQt.
To create an executable of the software I ship with it a Python and a Qt precompiled version and the trick seems to work in windows and linux since I know How to create an istaller.
The problem is to embed evrything into a mac .app
To launch the software I use the following shel script
export DYLD_LIBRARY_PATH=`pwd`/lib:$DYLD_LIBRARY_PATH
export DYLD_FRAMEWORK_PATH=`pwd`/Resources
PYTHONPATH=$PYTHONPATH:. bin/python ProgramPy/Main.py
If I run this shell script from outside it works fine but when I try to embed everything into an app with platypus I get the following error.
dyld: Library not loaded: @executable_path/../.Python
Referenced from: /Users/luca/Desktop/TempScript.app/Contents/Resources/bin/python
Reason: image not found
./run.sh: line 3: 725 Trace/BPT trap PYTHONPATH=$PYTHONPATH:. bin/python ProgramPy/Main.py
Note that the file /Users/luca/Desktop/TempScript.app/Contents/Resources/bin/python
is the executable version of python and it is actually located into the Resources folder of the app. I don't understand why the system cannot find it...
Maybe I miss something in understanding how mac uses the pythonpath ...
Thanks
| [
"I just use py2app.\n"
] | [
3
] | [] | [] | [
"macos",
"python",
"shipping"
] | stackoverflow_0004206511_macos_python_shipping.txt |
Q:
Source Code in Bullet Lists with reStructuredText
I am trying to include source code in bullet lists with reStructuredText; like this:
- List item 1 ::
code sample...
code sample...
- List item 2 ::
code sample...
code sample...
However, I get the following warning:
System Message: WARNING/2
Literal block expected; none found.
The empty lines in the list are indented by a single space. Any ideas?
A:
You haven't indented enough. Think of it this way.
- List item 1
::
code sample...
code sample...
- List item 2
::
code sample...
code sample...
| Source Code in Bullet Lists with reStructuredText | I am trying to include source code in bullet lists with reStructuredText; like this:
- List item 1 ::
code sample...
code sample...
- List item 2 ::
code sample...
code sample...
However, I get the following warning:
System Message: WARNING/2
Literal block expected; none found.
The empty lines in the list are indented by a single space. Any ideas?
| [
"You haven't indented enough. Think of it this way.\n- List item 1 \n ::\n\n code sample...\n code sample...\n\n- List item 2 \n ::\n\n code sample...\n code sample...\n\n"
] | [
38
] | [] | [] | [
"documentation",
"python",
"restructuredtext"
] | stackoverflow_0004206393_documentation_python_restructuredtext.txt |
Q:
Django + apache & mod_wsgi: having to restart apache after changes
I configured my development server this way:
Ubuntu, Apache, mod_wsgi, Python 2.6
I work on the server from another computer connected to it.
Most of the times the changes don't affect the application unless I restart Apache.
In some cases the changes take effect without restarting the webserver, but after let's say 3 or 4 page loads the application might behave like it used to behave previous to the changes.
Until now I just reloaded everytime apache as I have the development server here with me, but HELL after a while got so annoying. How can I avoid this?
I can't work with the development server as I need an environment that is as close as possible as the production one.
Thanks
A:
My suggestion is that you run the application in daemon mode.
This way you won't be required to restart apache,
just touch my_handler.wsgi and the daemon will know to restart the app. The apache httpd will not be only yours (in production) so it is fair not to restart it on every update.
A:
No changes require you to RESTART. You simply need to reload using "sudo /etc/init.d/apache2 reload". Which I have aliased in my bashrc to 'a2reload'.
function a2reload (){
sudo /etc/init.d/apache2 reload
}
A:
Apache loads Django environment when starting and keep running it even when source is changed.
I suggest you to use Django 'runserver' (which automatically restarts on changes) in heavy development sessions, unless you need some Apache-specific features (such as multi-thread).
Note also that changes in templates do not require the restart of the web server.
| Django + apache & mod_wsgi: having to restart apache after changes | I configured my development server this way:
Ubuntu, Apache, mod_wsgi, Python 2.6
I work on the server from another computer connected to it.
Most of the times the changes don't affect the application unless I restart Apache.
In some cases the changes take effect without restarting the webserver, but after let's say 3 or 4 page loads the application might behave like it used to behave previous to the changes.
Until now I just reloaded everytime apache as I have the development server here with me, but HELL after a while got so annoying. How can I avoid this?
I can't work with the development server as I need an environment that is as close as possible as the production one.
Thanks
| [
"My suggestion is that you run the application in daemon mode. \nThis way you won't be required to restart apache,\njust touch my_handler.wsgi and the daemon will know to restart the app. The apache httpd will not be only yours (in production) so it is fair not to restart it on every update.\n",
"No changes requi... | [
22,
6,
0
] | [] | [] | [
"apache",
"django",
"django_wsgi",
"mod_wsgi",
"python"
] | stackoverflow_0004206000_apache_django_django_wsgi_mod_wsgi_python.txt |
Q:
How to generate several matplotlib charts at a time?
I would like to generate several charts and save them as .png files.
But it seems matplotlib is overlapping the next chart on the previous one :
def do_pie(fic,data):
import pylab
# make a square figure and axes
pylab.figure(1, figsize=(6,6))
ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
pylab.pie(data,labels=data)
pylab.title(fic, bbox={'facecolor':'0.8', 'pad':5})
pylab.savefig('%s.png' % fic,dpi=100)
do_pie('tarte',[10,20,30])
do_pie('gateau',[33,44])
This script generate 2 PNG files.
tarte.png is correct, but gateau.png is getting some informations about tarte.png like 10, 20 and 30 that should not be displayed.
So how to start a new chart from scratch ?
A:
Just close the figure object after you save it.
def do_pie(fic,data):
import pylab
# make a square figure and axes
pylab.figure(1, figsize=(6,6))
ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
pylab.pie(data,labels=data)
pylab.title(fic, bbox={'facecolor':'0.8', 'pad':5})
pylab.savefig('%s.png' % fic,dpi=100)
pylab.close()
A:
For example, you can store figure instance in a dict and at the end of your program, output all figures:
figures = dict()
def do_pie(fic,data):
import pylab
# make a square figure and axes
figures[fic] = pylab.figure(figsize=(6,6))
ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
pylab.pie(data,labels=data)
pylab.title(fic, bbox={'facecolor':'0.8', 'pad':5})
do_pie('tarte',[10,20,30])
do_pie('gateau',[33,44])
for fig in figures:
figures[fig].savefig('%s.png' % fic, dpi=100)
| How to generate several matplotlib charts at a time? | I would like to generate several charts and save them as .png files.
But it seems matplotlib is overlapping the next chart on the previous one :
def do_pie(fic,data):
import pylab
# make a square figure and axes
pylab.figure(1, figsize=(6,6))
ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
pylab.pie(data,labels=data)
pylab.title(fic, bbox={'facecolor':'0.8', 'pad':5})
pylab.savefig('%s.png' % fic,dpi=100)
do_pie('tarte',[10,20,30])
do_pie('gateau',[33,44])
This script generate 2 PNG files.
tarte.png is correct, but gateau.png is getting some informations about tarte.png like 10, 20 and 30 that should not be displayed.
So how to start a new chart from scratch ?
| [
"Just close the figure object after you save it.\ndef do_pie(fic,data):\n import pylab \n # make a square figure and axes\n pylab.figure(1, figsize=(6,6))\n ax = pylab.axes([0.1, 0.1, 0.8, 0.8])\n pylab.pie(data,labels=data)\n pylab.title(fic, bbox={'facecolor':'0.8', 'pad':5})\n pylab.savef... | [
3,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004206175_matplotlib_python.txt |
Q:
How to create a datetime object with PyYAML
I'd like to be able to create a datetime object with datetime.datetime.now() PyYAML. It's easy to call some functions:
>>> y = """#YAML
... description: Something
... ts: !!python/object/apply:time.time []"""
>>> yaml.load(y)
{'description': 'Something', 'ts': 1289955567.940973}
>>>
However, I can't seem to figure out how to get a datetime.now(). I've tried as many permutations with calls to that using the various python yaml tags.
These all fail:
tests = [
'dt: !!python/object:datetime.datetime.now []',
'dt: !!python/object/new:datetime.datetime.now []',
'dt: !!python/object/apply:datetime.datetime.now []',
]
for y in tests:
try:
print yaml.load(y)
except Exception, err:
print '==>', err
A:
I think this example achieves what you're looking for:
dt = yaml.load("""dt: !!python/object/apply:apply
- !!python/object/apply:getattr
- !!python/name:datetime.datetime
- now
- []
""")
However, I think it is too far-fetched because the !!python/object syntax supported by PyYAML is not supposed to call class methods (datetime.datetime.now is actually like a "static" factory method for datetime objects). As you said, this is simpler (though not what you're looking for):
dt = yaml.load("dt: !!python/object/apply:time.gmtime []")
dt = yaml.load("dt: !!python/object/apply:time.time []")
Another possible work-around would be to create a custom helper function that wraps the call to datetime.datetime.now so that it is easily serialized with !!python/object/apply. The cons is that this serialization would not be portable to an environment where this custom function is not found.
Anyway, in my opinion it does not make too much sense to serialize a value that always returns the current datetime (which would actually be the time when the YAML was parsed). PyYAML provides this shortcut for serializing a certain timestamp:
dt = yaml.load("""dt: !!timestamp '2010-11-17 13:12:11'""")
| How to create a datetime object with PyYAML | I'd like to be able to create a datetime object with datetime.datetime.now() PyYAML. It's easy to call some functions:
>>> y = """#YAML
... description: Something
... ts: !!python/object/apply:time.time []"""
>>> yaml.load(y)
{'description': 'Something', 'ts': 1289955567.940973}
>>>
However, I can't seem to figure out how to get a datetime.now(). I've tried as many permutations with calls to that using the various python yaml tags.
These all fail:
tests = [
'dt: !!python/object:datetime.datetime.now []',
'dt: !!python/object/new:datetime.datetime.now []',
'dt: !!python/object/apply:datetime.datetime.now []',
]
for y in tests:
try:
print yaml.load(y)
except Exception, err:
print '==>', err
| [
"I think this example achieves what you're looking for:\ndt = yaml.load(\"\"\"dt: !!python/object/apply:apply\n - !!python/object/apply:getattr\n - !!python/name:datetime.datetime\n - now\n - []\n\"\"\")\n\nHowever, I think it is too far-fetched because the !!python/object syntax supported by Py... | [
9
] | [] | [] | [
"python",
"pyyaml",
"yaml"
] | stackoverflow_0004200627_python_pyyaml_yaml.txt |
Q:
Scratch disks in Python?
I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?
I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?
A:
Until you ACTUALLY run out of memory, thinking about this is a waste of time.
When you finally do run out of memory, you'll need to use a temporary file to store objects that your process needs, but can't fit into memory.
Use pickle or shelve (see Data Persistence) your objects in a file. If that file happens to be on a disk named "scratch", well that's nice.
Sometimes you want your temporary files to be on a separate disk from your other working files for performance reasons. In some environments (SAN, NAS, storage arrays) your disks are virtual and looking for a "scratch" disk doesn't have any performance benefit. In other environments (i.e., you own all the hardware) you can put temporary files on some other drive, making that drive a "scratch" disk.
A:
I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB.
Just an FYI, this is more a limitation of a 32-bit OS rather than being a Windows XP problem. You'll have the same problem in 32-bit Vista, linux, bsd... you get the idea. If you go the 64-bit route, you don't have these problems.
For example, Windows XP x64 allows up to 8 terabytes of memory per process.
A:
Scratch disks will benefit your application in the case that it works with very big files,
Is that the case?
If not, then i don't think you may find something that will benefit your application in scratch disks.
A:
Memory mapped files might be what you are looking for. Python's implementation lets you use a file like a mutable string in memory.
A:
The Win32 API provides this: link text.
You may be able to use these functions through PyWin32.
A:
You could combine S.Lott's answer about using pickle (you should use cPickle though for better performance) with SqlLite.
sqlite is built into python 2.5 and up, so all you'll need to do is import :), then just store the pickled objects as strings in there and you'll have a nice fast method of accessing the data (compared to building your own method) that will help keep you organized as well.
note: cPickle is almost identical to pickle in use. Only difference is that it is written in C
Useful Python Docs:
sqlite3 module
pickle module
edit: It may be a good idea to have a user controlled memory usage limit. It would be a shame to be storing a bunch a data on disk and waiting on slow-ass disk I/O when the user has 8GB of RAM ;)
A:
You are probably looking for something like ZODB. However, though ZODB tries hard to be transparent, no solution is going to be 100% free of artifacts. You have to write your code with an awareness that your objects primarily live in a database, but that there are multiple representations of your objects, there are caching/syncing issues, etc. Nothing is going to make this very difficult problem completely trivial for you.
| Scratch disks in Python? | I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?
I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?
| [
"Until you ACTUALLY run out of memory, thinking about this is a waste of time.\nWhen you finally do run out of memory, you'll need to use a temporary file to store objects that your process needs, but can't fit into memory.\nUse pickle or shelve (see Data Persistence) your objects in a file. If that file happens t... | [
4,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"memory_management",
"python",
"windows"
] | stackoverflow_0000737947_memory_management_python_windows.txt |
Q:
Determine "wiggliness" of set of data - Python
I'm working on a piece of software which needs to implement the wiggliness of a set of data. Here's a sample of the input I would receive, merged with the lightness plot of each vertical pixel strip:
It is easy to see that the left margin is really wiggly (i.e. has a ton of minima/maxima), and I want to generate a set of critical points of the image. I've applied a Gaussian smoothing function to the data ~ 10 times, but it seems to be pretty wiggly to begin with.
Any ideas?
Here's my original code, but it does not produce very nice results (for the wiggliness):
def local_maximum(list, center, delta):
maximum = [0, 0]
for i in range(delta):
if list[center + i] > maximum[1]: maximum = [center + i, list[center + i]]
if list[center - i] > maximum[1]: maximum = [center - i, list[center - i]]
return maximum
def count_maxima(list, start, end, delta, threshold = 10):
count = 0
for i in range(start + delta, end - delta):
if abs(list[i] - local_maximum(list, i, delta)[1]) < threshold: count += 1
return count
def wiggliness(list, start, end, delta, threshold = 10):
return float(abs(start - end) * delta) / float(count_maxima(list, start, end, delta, threshold))
A:
Take a look at lowpass/highpass/notch/bandpass filters, fourier transforms, or wavelets. The basic idea is there's lots of different ways to figure out the frequency content of a signal quantized over different time-periods.
If we can figure out what wiggliness is, that would help. I would say the leftmost margin is wiggly b/c it has more high-frequency content, which you could visualize by using a fourier transform.
If you take a highpass filter of that red signal, you'll get just the high frequency content, and then you can measure the amplitudes and do thresholds to determine wiggliness. But I guess wiggliness just needs more formalism behind it.
A:
For things like these, numpy makes things much easier, as it provides useful functions for manipulating vector data, e.g. adding a scalar to each element, calculating the average value etc.
For example, you might try with zero crossing rate of either the original data-wiggliness1 or the first difference-wiggliness2 (depending on what wiggliness is supposed to be, exactly-if global trends are to be ignored, you should probably use the difference data). For x you would take the slice or window of interest from the original data, getting a sort of measure of local wiggliness.
If you use the original data, after removing the bias you might also want to set all values smaller than some threshold to 0 to ignore low-amplitude wiggles.
import numpy as np
def wiggliness1(x):
#remove bias:
x=x-np.average(x)
#calculate zero crossing rate:
np.sum(np.abs(np.sign(np.diff(x))))
def wiggliness(x):
#calculate zero crossing rate of the first difference:
return np.sum(np.abs(np.sign(np.diff(np.sign(np.diff(x))))))
| Determine "wiggliness" of set of data - Python | I'm working on a piece of software which needs to implement the wiggliness of a set of data. Here's a sample of the input I would receive, merged with the lightness plot of each vertical pixel strip:
It is easy to see that the left margin is really wiggly (i.e. has a ton of minima/maxima), and I want to generate a set of critical points of the image. I've applied a Gaussian smoothing function to the data ~ 10 times, but it seems to be pretty wiggly to begin with.
Any ideas?
Here's my original code, but it does not produce very nice results (for the wiggliness):
def local_maximum(list, center, delta):
maximum = [0, 0]
for i in range(delta):
if list[center + i] > maximum[1]: maximum = [center + i, list[center + i]]
if list[center - i] > maximum[1]: maximum = [center - i, list[center - i]]
return maximum
def count_maxima(list, start, end, delta, threshold = 10):
count = 0
for i in range(start + delta, end - delta):
if abs(list[i] - local_maximum(list, i, delta)[1]) < threshold: count += 1
return count
def wiggliness(list, start, end, delta, threshold = 10):
return float(abs(start - end) * delta) / float(count_maxima(list, start, end, delta, threshold))
| [
"Take a look at lowpass/highpass/notch/bandpass filters, fourier transforms, or wavelets. The basic idea is there's lots of different ways to figure out the frequency content of a signal quantized over different time-periods.\nIf we can figure out what wiggliness is, that would help. I would say the leftmost marg... | [
5,
1
] | [] | [] | [
"frequency_analysis",
"frequency_distribution",
"list",
"python",
"statistics"
] | stackoverflow_0004191674_frequency_analysis_frequency_distribution_list_python_statistics.txt |
Q:
Getting last (newest) element with lxml,python
Hey everyone, I have had some amazing help the past couple days in trying to solve my issue. I just have one last questions (I hope) :)
I am trying to get the last element from my xml and place it in a variable. I am using django,python and the lxml library.
What I want to do is, go through the XML that I have got from the API call, find the newest project, (it will have the largest ID number) then assign it to a variable to store in my database. I am having some trouble finding out how to find that latest, newest, element.
Here is a code snippet:
req2 = urllib2.Request("http://web_url/public/api.php?path_info=/projects&token=#########")
resp = urllib2.urlopen(req2)
resp_data = resp.read()
if not resp.code == '200' and resp.headers.get('content-type') == 'text/xml':
# Do your error handling.
raise Exception('Unexpected response',req2,resp)
data = etree.XML(resp_data)
#assigns the api_id to the id at index of 0 for time being, using the // in front of project makes sure that its looking at the correct node inside of the projects structure
api_id = int(data.xpath('//project/id/text()')[0])
project.API_id = api_id
project.save()
As of right now, it takes the element at [0] and stores the ID just fine, but I need the latest/newest/etc element instead.
Thanks,
Steve
A:
Change [0] to [-1] to select the last element in the list:
api_id = int(data.xpath('//project/id/text()')[-1])
Note that this may not give you the largest id value if the largest is not at the end of the list.
To get the largest id, you could do this:
api_id = max(map(int,data.xpath('//project/id/text()')))
| Getting last (newest) element with lxml,python | Hey everyone, I have had some amazing help the past couple days in trying to solve my issue. I just have one last questions (I hope) :)
I am trying to get the last element from my xml and place it in a variable. I am using django,python and the lxml library.
What I want to do is, go through the XML that I have got from the API call, find the newest project, (it will have the largest ID number) then assign it to a variable to store in my database. I am having some trouble finding out how to find that latest, newest, element.
Here is a code snippet:
req2 = urllib2.Request("http://web_url/public/api.php?path_info=/projects&token=#########")
resp = urllib2.urlopen(req2)
resp_data = resp.read()
if not resp.code == '200' and resp.headers.get('content-type') == 'text/xml':
# Do your error handling.
raise Exception('Unexpected response',req2,resp)
data = etree.XML(resp_data)
#assigns the api_id to the id at index of 0 for time being, using the // in front of project makes sure that its looking at the correct node inside of the projects structure
api_id = int(data.xpath('//project/id/text()')[0])
project.API_id = api_id
project.save()
As of right now, it takes the element at [0] and stores the ID just fine, but I need the latest/newest/etc element instead.
Thanks,
Steve
| [
"Change [0] to [-1] to select the last element in the list:\napi_id = int(data.xpath('//project/id/text()')[-1])\n\nNote that this may not give you the largest id value if the largest is not at the end of the list.\nTo get the largest id, you could do this:\napi_id = max(map(int,data.xpath('//project/id/text()')))\... | [
5
] | [] | [] | [
"django",
"django_views",
"lxml",
"python"
] | stackoverflow_0004207012_django_django_views_lxml_python.txt |
Q:
Named entity recognition with preset list of names for Python / PHP
I'm trying to process a CSV file that has as in each row a text field with the name of organization and position of an individual within that organization as unstructured text. This field is usually a mess of text like this:
Assoc. Research Professor Dept. Psychology Univ. California Santa Barbara
I need to pull out the position and the organization name. For the position, I use preg_match for a series of about 60 different regular expressions for the different professions, and I think it works pretty well (my guess is that it catches about 80%). But, I'm having trouble catching the organization name. I have a MySQL table with roughly 16,000 organization names that I can perform a simple preg_match for, but due to common misspellings and abbreviations, it's only catching about 30% of the organizations. For example, my database has
University of California Santa Barbara
But the CSV file might have any of the options:
Univ Cal Santa Barbara
University Cal-Santa Barbara
University California-Santa Barbara
Cal University, Santa Barbara
I need to process several hundred thousand records, and I can't spend the time to correct 70% of the records that are currently not being processed correctly or painstakingly create multiple aliases for each organization. What I would like to be able to do is to catch small differences (such as the small misspellings, hyphens versus spaces, and common abbreviations), and, if still no matches are found, to ideally recognize an organizational name and create a new record for it.
What libraries or tools in Python or PHP would allow to perform a similarity match that would have a broader reach?
Would NLTK in Python catch misspellings?
Is it possible to use AlchemyAPI to catch misspelled organizations? So far I've only been able to use it to catch correctly spelled organizations
Since I'm comparing a short string (the organization name) to a longer string (that includes the name plus extraneous information) is there any hope in using PHP's similar_text function?
Any help or insight would be appreciated.
A:
This is within the domain of fuzzy logic. See if these are of any help:
http://www.phpclasses.org/blog/post/119-Neural-Networks-in-PHP.html
http://ann.thwien.de/index.php/Installation
A:
You may be able to use difflib to calculate the similarity ratio between the CSV input and the canonical spelling, and consider it a match if it's above a certain threshold (say, 0.65).
For example:
import difflib
exact = 'University of California Santa Barbara'
inputs = ['Univ Cal Santa Barbara',
'University Cal-Santa Barbara',
'University California-Santa Barbara',
'Cal University, Santa Barbara',
'Canterbury University']
sm = difflib.SequenceMatcher(None, exact)
ratios = []
for input in inputs:
sm.set_seq2(input)
ratios.append(sm.ratio())
print ratios
gives:
[0.73333333333333328, 0.81818181818181823, 0.93150684931506844,
0.71641791044776115, 0.33898305084745761]
Note how 'Canterbury University' has a much lower match ratio() than the inputs you gave.
Then again, SequenceMatcher.ratio() may be too slow computed over 16,000 values.
| Named entity recognition with preset list of names for Python / PHP | I'm trying to process a CSV file that has as in each row a text field with the name of organization and position of an individual within that organization as unstructured text. This field is usually a mess of text like this:
Assoc. Research Professor Dept. Psychology Univ. California Santa Barbara
I need to pull out the position and the organization name. For the position, I use preg_match for a series of about 60 different regular expressions for the different professions, and I think it works pretty well (my guess is that it catches about 80%). But, I'm having trouble catching the organization name. I have a MySQL table with roughly 16,000 organization names that I can perform a simple preg_match for, but due to common misspellings and abbreviations, it's only catching about 30% of the organizations. For example, my database has
University of California Santa Barbara
But the CSV file might have any of the options:
Univ Cal Santa Barbara
University Cal-Santa Barbara
University California-Santa Barbara
Cal University, Santa Barbara
I need to process several hundred thousand records, and I can't spend the time to correct 70% of the records that are currently not being processed correctly or painstakingly create multiple aliases for each organization. What I would like to be able to do is to catch small differences (such as the small misspellings, hyphens versus spaces, and common abbreviations), and, if still no matches are found, to ideally recognize an organizational name and create a new record for it.
What libraries or tools in Python or PHP would allow to perform a similarity match that would have a broader reach?
Would NLTK in Python catch misspellings?
Is it possible to use AlchemyAPI to catch misspelled organizations? So far I've only been able to use it to catch correctly spelled organizations
Since I'm comparing a short string (the organization name) to a longer string (that includes the name plus extraneous information) is there any hope in using PHP's similar_text function?
Any help or insight would be appreciated.
| [
"This is within the domain of fuzzy logic. See if these are of any help:\nhttp://www.phpclasses.org/blog/post/119-Neural-Networks-in-PHP.html\nhttp://ann.thwien.de/index.php/Installation\n",
"You may be able to use difflib to calculate the similarity ratio between the CSV input and the canonical spelling, and con... | [
2,
1
] | [] | [] | [
"named_entity_recognition",
"nlp",
"php",
"python",
"text"
] | stackoverflow_0004206882_named_entity_recognition_nlp_php_python_text.txt |
Q:
How do I iterate through all possible values in a series of fixed lists?
(python)
so I have the following values & lists:
name = colour
size = ['256', '512', '1024', '2048', '4096', '8192', '16384', '32768']
depth = ['8', '16', '32']
scalar = ['False', 'True']
alpha = ['False', 'True']
colour = app.Color(0.5)
and I want to iterate over these to produce every possible combination with the following structure:
createChannel(ChannelInfo(name, size, depth, scalar, alpha, colour))
so the values for name, size, etc must stay in the same place, but they must iterate over all possible combinations of size, depth, etc..
i.e. I want to return something like this:
createChannel(ChannelInfo('colour', 256, 8, False, True, 0.5)
createChannel(ChannelInfo('colour1', 256, 8, False, False, 0.5)
createChannel(ChannelInfo('colour2', 256, 16, False, False, 0.5)
...etc...there are 96 combinations
Thanks
A:
import itertools
for iter in itertools.product(size, depth, scalar, alpha):
print iter # prints 96 four-element tuples
A:
from itertools import product
# generates all the possible values
combinations = product(size, depth, scalar, alpha)
# call the function for each combination
# i guess `names` is a list of 96 names ..
items = [createChannel(ChannelInfo(name, *row))
for name, row in zip(names, combinations)]
A:
I recently had the same requirement. I borrowed this cross-product function from here.
def cross(*sequences):
# visualize an odometer, with "wheels" displaying "digits"...:
wheels = map(iter, sequences)
digits = [it.next() for it in wheels]
while True:
yield tuple(digits)
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = wheels[i].next()
break
except StopIteration:
wheels[i] = iter(sequences[i])
digits[i] = wheels[i].next()
else:
break
Pass it a set of lists and it will return a generator which iterates as you specified above.
| How do I iterate through all possible values in a series of fixed lists? | (python)
so I have the following values & lists:
name = colour
size = ['256', '512', '1024', '2048', '4096', '8192', '16384', '32768']
depth = ['8', '16', '32']
scalar = ['False', 'True']
alpha = ['False', 'True']
colour = app.Color(0.5)
and I want to iterate over these to produce every possible combination with the following structure:
createChannel(ChannelInfo(name, size, depth, scalar, alpha, colour))
so the values for name, size, etc must stay in the same place, but they must iterate over all possible combinations of size, depth, etc..
i.e. I want to return something like this:
createChannel(ChannelInfo('colour', 256, 8, False, True, 0.5)
createChannel(ChannelInfo('colour1', 256, 8, False, False, 0.5)
createChannel(ChannelInfo('colour2', 256, 16, False, False, 0.5)
...etc...there are 96 combinations
Thanks
| [
"import itertools\nfor iter in itertools.product(size, depth, scalar, alpha):\n print iter # prints 96 four-element tuples\n\n",
"from itertools import product\n\n# generates all the possible values\ncombinations = product(size, depth, scalar, alpha)\n# call the function for each combination\n# i guess `names`... | [
7,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004207122_python.txt |
Q:
taking log of very small values using numpy/scipy in Python
I have an Nx1 array that corresponds to a probability distribution, i.e. the sum of the elements sums to 1. This is represented as a regular numpy array. Since N might be relatively large, e.g. 10 or 20, many of the individual elements are pretty close to 0. I find that when I take log(my_array), I get the error "FloatingPointError: invalid value encountered in log". Note that this is after setting seterr(invalid='raise') in numpy intentionally.
How can I deal with this numerical issue? I'd like to represent vectors corresponding to a probability distribution and their take log without rounding to 0, since then I end up taking log(0) which raises the error.
thanks.
A:
You can just drop the tails according to the accuracy you need.
eps = 1e-50
array[array<eps]=eps
log(array)
A:
What's pretty close to zero ?
>>> np.log(0)
-inf
>>> 0.*np.log(0)
nan
>>> np.log(1e-200)
-460.51701859880916
>>> 1e-200*np.log(1e-200)
-4.6051701859880914e-198
One solution is to add a small positive number to all probabilities to restrict them to be far enough away from zero.
The second solution is to handle zeros explicitly, for example replace 0.*np.log(0) with zeros in the resulting array, or only include points that have nonzero probability in the probability array
A:
How 'pretty close' to 0 are they? Python seems happy taking log of 10^-very large:
>>> log(0.0000000000000000000000000001)
-64.472382603833282
Also, why are you taking logs? What do you plan to do with them once you've took them?
A:
Depending on what you're doing afterwards, you could use a different transform that doesn't explode on zero values like log does. Perhaps a sigmoid function or something else with a well-defined Jacobian.
If you're just looking to visualize the data, you could always add some tiny value before you take the log.
| taking log of very small values using numpy/scipy in Python | I have an Nx1 array that corresponds to a probability distribution, i.e. the sum of the elements sums to 1. This is represented as a regular numpy array. Since N might be relatively large, e.g. 10 or 20, many of the individual elements are pretty close to 0. I find that when I take log(my_array), I get the error "FloatingPointError: invalid value encountered in log". Note that this is after setting seterr(invalid='raise') in numpy intentionally.
How can I deal with this numerical issue? I'd like to represent vectors corresponding to a probability distribution and their take log without rounding to 0, since then I end up taking log(0) which raises the error.
thanks.
| [
"You can just drop the tails according to the accuracy you need.\neps = 1e-50\narray[array<eps]=eps\nlog(array)\n\n",
"What's pretty close to zero ?\n>>> np.log(0)\n-inf\n>>> 0.*np.log(0)\nnan\n>>> np.log(1e-200)\n-460.51701859880916\n>>> 1e-200*np.log(1e-200)\n-4.6051701859880914e-198\n\nOne solution is to add a... | [
3,
2,
1,
0
] | [] | [] | [
"numerical_methods",
"numpy",
"python",
"scipy"
] | stackoverflow_0004206528_numerical_methods_numpy_python_scipy.txt |
Q:
how to set up environment variables for python
On WinXP sp2 I'd like to have a directory of modules that other python scripts will be using called "SharedPython" in the same directory as my python scripts. so, basically:
/pythonScripts
/pythonScripts/SharedPython
as well as other python scripts on the same level as the SharedPython directory.
when I run
print sys.path
I get the following output:
C:\WINDOWS\system32\python25.zip
C:\Python25\DLLs
C:\Python25\lib
C:\Python25\lib\plat-win
C:\Python25\lib\lib-tk
C:\Python25
C:\Python25\lib\site-packages
I don't know what environment variable controls this and, in fact, I don't see one that contains all these directories.
So,
a.)how do I determine which environment variable contains this list of dirs?
and
b.)can I just add the aforementioned SharedPython dir to that list?
I've tried setting PYTHONPATH to the following: %PYTHONPATH%C:\PythonScripts\SharedPython
A:
You need the PYTHONPATH env var. The dirs listed in it are prepended to sys.path.
The correct way to setup PYTHONPATH in your case is:
set PYTHONPATH=%PYTHONPATH%;C:\PythonScripts\SharedPython
Note the semicolon between the second % and the C:\
A:
Those paths are added by the site module; do not change this module, but rather create a batch file that adds your paths in %PYTHONPATH% and then runs the script.
| how to set up environment variables for python | On WinXP sp2 I'd like to have a directory of modules that other python scripts will be using called "SharedPython" in the same directory as my python scripts. so, basically:
/pythonScripts
/pythonScripts/SharedPython
as well as other python scripts on the same level as the SharedPython directory.
when I run
print sys.path
I get the following output:
C:\WINDOWS\system32\python25.zip
C:\Python25\DLLs
C:\Python25\lib
C:\Python25\lib\plat-win
C:\Python25\lib\lib-tk
C:\Python25
C:\Python25\lib\site-packages
I don't know what environment variable controls this and, in fact, I don't see one that contains all these directories.
So,
a.)how do I determine which environment variable contains this list of dirs?
and
b.)can I just add the aforementioned SharedPython dir to that list?
I've tried setting PYTHONPATH to the following: %PYTHONPATH%C:\PythonScripts\SharedPython
| [
"You need the PYTHONPATH env var. The dirs listed in it are prepended to sys.path.\nThe correct way to setup PYTHONPATH in your case is:\nset PYTHONPATH=%PYTHONPATH%;C:\\PythonScripts\\SharedPython\n\nNote the semicolon between the second % and the C:\\\n",
"Those paths are added by the site module; do not chang... | [
5,
1
] | [] | [] | [
"environment_variables",
"python"
] | stackoverflow_0004207173_environment_variables_python.txt |
Q:
Parse WAV file header
I am writing a program to parse a WAV file header and print the information to the screen. Before writing the program i am doing some research
hexdump -n 48 sound_file_8000hz.wav
00000000 52 49 46 46 bc af 01 00 57 41 56 45 66 6d 74 20 |RIFF....WAVEfmt |
00000010 10 00 00 00 01 00 01 00 >40 1f 00 00< 40 1f 00 00 |........@...@...|
00000020 01 00 08 00 64 61 74 61 98 af 01 00 81 80 81 80 |....data........|
hexdump -n 48 sound_file_44100hz.wav
00000000 52 49 46 46 c4 ea 1a 00 57 41 56 45 66 6d 74 20 |RIFF....WAVEfmt |
00000010 10 00 00 00 01 00 02 00 >44 ac 00 00< 10 b1 02 00 |........D.......|
00000020 04 00 10 00 64 61 74 61 a0 ea 1a 00 00 00 00 00 |....data........|
The part between > and < in both files are the sample rate.
How does "40 1f 00 00" translate to 8000Hz and "44 ac 00 00" to 44100Hz? Information like number of channels and audio format can be read directly from the dump. I found a Python
script called WavHeader that parses the sample rate correctly in both files. This is the core of the script:
bufHeader = fileIn.read(38)
# Verify that the correct identifiers are present
if (bufHeader[0:4] != "RIFF") or \
(bufHeader[12:16] != "fmt "):
logging.debug("Input file not a standard WAV file")
return
# endif
stHeaderFields = {'ChunkSize' : 0, 'Format' : '',
'Subchunk1Size' : 0, 'AudioFormat' : 0,
'NumChannels' : 0, 'SampleRate' : 0,
'ByteRate' : 0, 'BlockAlign' : 0,
'BitsPerSample' : 0, 'Filename': ''}
# Parse fields
stHeaderFields['ChunkSize'] = struct.unpack('<L', bufHeader[4:8])[0]
stHeaderFields['Format'] = bufHeader[8:12]
stHeaderFields['Subchunk1Size'] = struct.unpack('<L', bufHeader[16:20])[0]
stHeaderFields['AudioFormat'] = struct.unpack('<H', bufHeader[20:22])[0]
stHeaderFields['NumChannels'] = struct.unpack('<H', bufHeader[22:24])[0]
stHeaderFields['SampleRate'] = struct.unpack('<L', bufHeader[24:28])[0]
stHeaderFields['ByteRate'] = struct.unpack('<L', bufHeader[28:32])[0]
stHeaderFields['BlockAlign'] = struct.unpack('<H', bufHeader[32:34])[0]
stHeaderFields['BitsPerSample'] = struct.unpack('<H', bufHeader[34:36])[0]
I do not understand how this can extract the corret sample rates, when i cannot using hexdump?
I am using information about the WAV file format from this page:
https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
A:
The "40 1F 00 00" bytes equate to an integer whose hexadecimal value is 00001F40 (remember that the integers are stored in a WAVE file in the little endian format). A value of 00001F40 in hexadecimal equates to a decimal value of 8000.
Similarly, the "44 AC 00 00" bytes equate to an integer whose hexadecimal value is 0000AC44. A value of 0000AC44 in hexadecimal equates to a decimal value of 44100.
A:
They're little-endian.
>>> 0x00001f40
8000
>>> 0x0000ac44
44100
| Parse WAV file header | I am writing a program to parse a WAV file header and print the information to the screen. Before writing the program i am doing some research
hexdump -n 48 sound_file_8000hz.wav
00000000 52 49 46 46 bc af 01 00 57 41 56 45 66 6d 74 20 |RIFF....WAVEfmt |
00000010 10 00 00 00 01 00 01 00 >40 1f 00 00< 40 1f 00 00 |........@...@...|
00000020 01 00 08 00 64 61 74 61 98 af 01 00 81 80 81 80 |....data........|
hexdump -n 48 sound_file_44100hz.wav
00000000 52 49 46 46 c4 ea 1a 00 57 41 56 45 66 6d 74 20 |RIFF....WAVEfmt |
00000010 10 00 00 00 01 00 02 00 >44 ac 00 00< 10 b1 02 00 |........D.......|
00000020 04 00 10 00 64 61 74 61 a0 ea 1a 00 00 00 00 00 |....data........|
The part between > and < in both files are the sample rate.
How does "40 1f 00 00" translate to 8000Hz and "44 ac 00 00" to 44100Hz? Information like number of channels and audio format can be read directly from the dump. I found a Python
script called WavHeader that parses the sample rate correctly in both files. This is the core of the script:
bufHeader = fileIn.read(38)
# Verify that the correct identifiers are present
if (bufHeader[0:4] != "RIFF") or \
(bufHeader[12:16] != "fmt "):
logging.debug("Input file not a standard WAV file")
return
# endif
stHeaderFields = {'ChunkSize' : 0, 'Format' : '',
'Subchunk1Size' : 0, 'AudioFormat' : 0,
'NumChannels' : 0, 'SampleRate' : 0,
'ByteRate' : 0, 'BlockAlign' : 0,
'BitsPerSample' : 0, 'Filename': ''}
# Parse fields
stHeaderFields['ChunkSize'] = struct.unpack('<L', bufHeader[4:8])[0]
stHeaderFields['Format'] = bufHeader[8:12]
stHeaderFields['Subchunk1Size'] = struct.unpack('<L', bufHeader[16:20])[0]
stHeaderFields['AudioFormat'] = struct.unpack('<H', bufHeader[20:22])[0]
stHeaderFields['NumChannels'] = struct.unpack('<H', bufHeader[22:24])[0]
stHeaderFields['SampleRate'] = struct.unpack('<L', bufHeader[24:28])[0]
stHeaderFields['ByteRate'] = struct.unpack('<L', bufHeader[28:32])[0]
stHeaderFields['BlockAlign'] = struct.unpack('<H', bufHeader[32:34])[0]
stHeaderFields['BitsPerSample'] = struct.unpack('<H', bufHeader[34:36])[0]
I do not understand how this can extract the corret sample rates, when i cannot using hexdump?
I am using information about the WAV file format from this page:
https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
| [
"The \"40 1F 00 00\" bytes equate to an integer whose hexadecimal value is 00001F40 (remember that the integers are stored in a WAVE file in the little endian format). A value of 00001F40 in hexadecimal equates to a decimal value of 8000.\nSimilarly, the \"44 AC 00 00\" bytes equate to an integer whose hexadecimal ... | [
8,
5
] | [] | [] | [
"python",
"wav"
] | stackoverflow_0004207326_python_wav.txt |
Q:
Why do elements in Python for ... in ...: statements use byValue behavior?
I can't seem to find an explanation anywhere for this...
Suppose I have a vector y initialized to all zeroes:
from numpy import *
y = zeros(5)
It could also be a plain python array, I don't think it really matters.
I noticed that the behavior of the for x in y: statement is that it makes a copy of each element in y, thus when you modify x, it does not modify y.
for x in y:
x = 1
print y
output : array([ 0., 0., 0., 0., 0.])
My question is the following : Why is that so? I thought in Python everything was all byReference and that there is very little byValue passing around?
How could I do the following, using referenced variables? Doing the following seems to work :
for i in range(len(y)):
y[i] = 2*rand()-1
But from what I know about Python, this is wrong and I believe it will be slow when I start using vectors of thousands or millions of values.
What else could I do?
A:
You can replace this:
y = np.zeros(5)
for i in range(len(y)):
y[i] = 2*rand()-1
with:
y=2*np.random.rand(5)-1
If y is a Python sequence (tuple, list, array, etc) or Numpy array,
for x in y:
iterates through y, setting x to each element in y.
If the elements are immutable objects like str, int, float or a Numpy numeric type,
then changing the value of x does not change the value in y.
If the elements are mutable objects, such as a list, then mutating the list will affect y.
Think of it this way: x is "pointing" to an object:
y---> [o----o----o----o]
^
|
x
When you write an assignment statement:
x += 1
Now you are reassigning x to "point" to a different object:
y---> [o----o----o----o]
x---> o
On the other hand, if you mutate a list with, say, x.append(1), then
x still points to the same object (e.g. a list), but you've mutated the contents of that list.
A:
Python does use "references" only. But what is called "reference" in Python (and Java, and propably a handful of other languages) is not like in "pass-by-reference" or "references in C++". When you iterate over something like for i in iterable:, i points to the current item. But when you do i = ... in the loop, you're overwriting that reference with a new one instead of replacing the object pointed to. So actually, Python (and all the other languages mentioned) are pass-by-value. Except that those values are always (kind of) pointers.
Note that this does not apply for i.attr = ...! Setting members is different, it's a method call (one of .__setitem__ of the object's __dict__, .__setattr__ or .__setattribute__ afaik). So if you did i.some_member in the loop, you would indeed alter the items of the iterable. Also note that this is of course moot with immutable objects like numbers or strings - you cannot possibly alter those.
If you want to alter e.g. a list directly, you need to use indices (although you shouldn't need range(len(...)), you can use enumerate(the_list) and you get indices and the current items). Also consider generating the values you want in the first place by using e.g. a list comprehension.
A:
Please someone correct me if I am wrong, but the integer type in Python is not mutable and that is why when you perform some operation on one of the elements of the vector you get back a new object. I looked and looked but haven't found any confirmation of this hunch but when I try
>>> def zeros(length):
... vector = []
... for each in range(length):
... vector.append([0])
... return vector
...
>>> zeros(8)
[[0], [0], [0], [0], [0], [0], [0], [0]]
>>> y = zeros(8)
>>> for x in y:
... x[0] += 1
...
>>> y
[[1], [1], [1], [1], [1], [1], [1], [1]]
and we know that lists are mutable we get what we expect.
A:
I don't see how that code sample is wrong at all - as long as y is accessible from the scope that the for loop is in, all should be good.
| Why do elements in Python for ... in ...: statements use byValue behavior? | I can't seem to find an explanation anywhere for this...
Suppose I have a vector y initialized to all zeroes:
from numpy import *
y = zeros(5)
It could also be a plain python array, I don't think it really matters.
I noticed that the behavior of the for x in y: statement is that it makes a copy of each element in y, thus when you modify x, it does not modify y.
for x in y:
x = 1
print y
output : array([ 0., 0., 0., 0., 0.])
My question is the following : Why is that so? I thought in Python everything was all byReference and that there is very little byValue passing around?
How could I do the following, using referenced variables? Doing the following seems to work :
for i in range(len(y)):
y[i] = 2*rand()-1
But from what I know about Python, this is wrong and I believe it will be slow when I start using vectors of thousands or millions of values.
What else could I do?
| [
"You can replace this:\ny = np.zeros(5)\nfor i in range(len(y)):\n y[i] = 2*rand()-1\n\nwith:\ny=2*np.random.rand(5)-1\n\n\nIf y is a Python sequence (tuple, list, array, etc) or Numpy array,\nfor x in y:\niterates through y, setting x to each element in y.\nIf the elements are immutable objects like str, int, f... | [
8,
4,
1,
0
] | [] | [] | [
"iteration",
"numpy",
"python"
] | stackoverflow_0004207231_iteration_numpy_python.txt |
Q:
Why is aptitude not installing python-mysqldb properly? ( error: No module named MySQLdb )
username@servername Tue Nov 02 22:08:28 ~/public_html/IDM_app
$ sudo aptitude install mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
libdbd-mysql-perl{a} libdbi-perl{a} libhtml-template-perl{a} libmysqlclient16{a}
libnet-daemon-perl{a} libplrpc-perl{a} mysql-client-5.1{a} mysql-client-core-5.1{a} mysql-common{a}
mysql-server mysql-server-5.1{a} mysql-server-core-5.1{a}
0 packages upgraded, 12 newly installed, 0 to remove and 44 not upgraded.
Need to get 0B/24.3MB of archives. After unpacking 60.9MB will be used.
Do you want to continue? [Y/n/?] Y
Writing extended state information... Done
Preconfiguring packages ...
Selecting previously deselected package mysql-common.
(Reading database ... 20736 files and directories currently installed.)
Unpacking mysql-common (from .../mysql-common_5.1.41-3ubuntu12.6_all.deb) ...
Selecting previously deselected package libnet-daemon-perl.
Unpacking libnet-daemon-perl (from .../libnet-daemon-perl_0.43-1_all.deb) ...
Selecting previously deselected package libplrpc-perl.
Unpacking libplrpc-perl (from .../libplrpc-perl_0.2020-2_all.deb) ...
Selecting previously deselected package libdbi-perl.
Unpacking libdbi-perl (from .../libdbi-perl_1.609-1build1_amd64.deb) ...
Selecting previously deselected package libmysqlclient16.
Unpacking libmysqlclient16 (from .../libmysqlclient16_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package libdbd-mysql-perl.
Unpacking libdbd-mysql-perl (from .../libdbd-mysql-perl_4.012-1ubuntu1_amd64.deb) ...
Selecting previously deselected package mysql-client-core-5.1.
Unpacking mysql-client-core-5.1 (from .../mysql-client-core-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package mysql-client-5.1.
Unpacking mysql-client-5.1 (from .../mysql-client-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package mysql-server-core-5.1.
Unpacking mysql-server-core-5.1 (from .../mysql-server-core-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Processing triggers for man-db ...
Setting up mysql-common (5.1.41-3ubuntu12.6) ...
Selecting previously deselected package mysql-server-5.1.
(Reading database ... 21101 files and directories currently installed.)
Unpacking mysql-server-5.1 (from .../mysql-server-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package libhtml-template-perl.
Unpacking libhtml-template-perl (from .../libhtml-template-perl_2.9-1_all.deb) ...
Selecting previously deselected package mysql-server.
Unpacking mysql-server (from .../mysql-server_5.1.41-3ubuntu12.6_all.deb) ...
Processing triggers for ureadahead ...
Processing triggers for man-db ...
Setting up libnet-daemon-perl (0.43-1) ...
Setting up libplrpc-perl (0.2020-2) ...
Setting up libdbi-perl (1.609-1build1) ...
Setting up libmysqlclient16 (5.1.41-3ubuntu12.6) ...
Setting up libdbd-mysql-perl (4.012-1ubuntu1) ...
Setting up mysql-client-core-5.1 (5.1.41-3ubuntu12.6) ...
Setting up mysql-client-5.1 (5.1.41-3ubuntu12.6) ...
Setting up mysql-server-core-5.1 (5.1.41-3ubuntu12.6) ...
Setting up mysql-server-5.1 (5.1.41-3ubuntu12.6) ...
mysql start/running, process 26154
Setting up libhtml-template-perl (2.9-1) ...
Setting up mysql-server (5.1.41-3ubuntu12.6) ...
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
Writing extended state information... Done
username@servername Tue Nov 02 22:09:21 ~/public_html/IDM_app
$ sudo aptitude install python-mysqldb
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
python-mysqldb python-support{a}
0 packages upgraded, 2 newly installed, 0 to remove and 44 not upgraded.
Need to get 0B/112kB of archives. After unpacking 504kB will be used.
Do you want to continue? [Y/n/?] y
Writing extended state information... Done
Selecting previously deselected package python-support.
(Reading database ... 21184 files and directories currently installed.)
Unpacking python-support (from .../python-support_1.0.4ubuntu1_all.deb) ...
Selecting previously deselected package python-mysqldb.
Unpacking python-mysqldb (from .../python-mysqldb_1.2.2-10build1_amd64.deb) ...
Processing triggers for man-db ...
Setting up python-support (1.0.4ubuntu1) ...
Setting up python-mysqldb (1.2.2-10build1) ...
Processing triggers for python-support ...
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
Writing extended state information... Done
username@servername Tue Nov 02 22:10:26 ~/public_html/IDM_app
$ python manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 13, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 67, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/contrib/contenttypes/generic.py", line 6, in <module>
from django.db import connection
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/__init__.py", line 77, in <module>
connection = connections[DEFAULT_DB_ALIAS]
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/utils.py", line 91, in __getitem__
backend = load_backend(db['ENGINE'])
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/utils.py", line 32, in load_backend
return import_module('.base', backend_name)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/backends/mysql/base.py", line 14, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
username@servername Wed Nov 03 03:24:00 ~/public_html/IDM_app
$ find / -name python-mysqldb 2>/dev/null
/usr/share/doc/python-mysqldb
username@servername Wed Nov 03 12:46:55 ~/public_html/IDM_app
$ ls /usr/local/mysql/bin/mysql_config
ls: cannot access /usr/local/mysql/bin/mysql_config: No such file or directory
username@servername Wed Nov 03 13:21:02 ~/public_html/IDM_app
$ find / -name mysql_config 2>/dev/null
username@servername Wed Nov 03 13:23:04 ~/public_html/IDM_app
$ find / -name python-mysqldb 2>/dev/null
/usr/share/doc/python-mysqldb
username@servername Wed Nov 03 13:29:01 ~/public_html/IDM_app
$ find / -name python-mysql 2>/dev/null
username@servername Wed Nov 03 13:29:21 ~/public_html/IDM_app
$ find / -name mysql 2>/dev/null
/etc/init.d/mysql
/etc/mysql
/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/contrib/gis/db/backends/mysql
/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/backends/mysql
/usr/share/mysql
/usr/bin/mysql
/usr/lib/perl5/auto/DBD/mysql
/usr/lib/perl5/DBD/mysql
/usr/lib/mysql
/var/log/mysql
/var/lib/update-rc.d/mysql
/var/lib/mysql
username@servername Wed Nov 03 13:30:21 ~/public_html/IDM_app
$ ls -la /usr/bin/mysql
-rwxr-xr-x 1 root 183376 Jul 29 22:54 /usr/bin/mysql
username@servername Wed Nov 03 13:35:01 ~/public_html/IDM_app
$ find / -name site.cfg 2>/dev/null
username@servername Wed Nov 03 13:44:04 ~/public_html/IDM_app
$ ls -la /usr/lib/mysql/
total 16
drwxr-xr-x 3 root 4096 Nov 2 22:09 .
drwxr-xr-x 42 root 8192 Nov 2 22:10 ..
drwxr-xr-x 2 root 4096 Nov 2 22:09 plugin
A:
The fix was:
sudo aptitude install libmysqlclient-dev
sudo easy_install MySQL-python
A:
First, try dpkg -L python-mysqldb, then you'll see what's installed.
Second, you are obviously using a manully compiled Python 2.7, while Ubuntu installs its packages for Python 2.6, which is the current default. You'll need to use easy_install to install python-mysql to your 2.7 installation.
| Why is aptitude not installing python-mysqldb properly? ( error: No module named MySQLdb ) | username@servername Tue Nov 02 22:08:28 ~/public_html/IDM_app
$ sudo aptitude install mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
libdbd-mysql-perl{a} libdbi-perl{a} libhtml-template-perl{a} libmysqlclient16{a}
libnet-daemon-perl{a} libplrpc-perl{a} mysql-client-5.1{a} mysql-client-core-5.1{a} mysql-common{a}
mysql-server mysql-server-5.1{a} mysql-server-core-5.1{a}
0 packages upgraded, 12 newly installed, 0 to remove and 44 not upgraded.
Need to get 0B/24.3MB of archives. After unpacking 60.9MB will be used.
Do you want to continue? [Y/n/?] Y
Writing extended state information... Done
Preconfiguring packages ...
Selecting previously deselected package mysql-common.
(Reading database ... 20736 files and directories currently installed.)
Unpacking mysql-common (from .../mysql-common_5.1.41-3ubuntu12.6_all.deb) ...
Selecting previously deselected package libnet-daemon-perl.
Unpacking libnet-daemon-perl (from .../libnet-daemon-perl_0.43-1_all.deb) ...
Selecting previously deselected package libplrpc-perl.
Unpacking libplrpc-perl (from .../libplrpc-perl_0.2020-2_all.deb) ...
Selecting previously deselected package libdbi-perl.
Unpacking libdbi-perl (from .../libdbi-perl_1.609-1build1_amd64.deb) ...
Selecting previously deselected package libmysqlclient16.
Unpacking libmysqlclient16 (from .../libmysqlclient16_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package libdbd-mysql-perl.
Unpacking libdbd-mysql-perl (from .../libdbd-mysql-perl_4.012-1ubuntu1_amd64.deb) ...
Selecting previously deselected package mysql-client-core-5.1.
Unpacking mysql-client-core-5.1 (from .../mysql-client-core-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package mysql-client-5.1.
Unpacking mysql-client-5.1 (from .../mysql-client-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package mysql-server-core-5.1.
Unpacking mysql-server-core-5.1 (from .../mysql-server-core-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Processing triggers for man-db ...
Setting up mysql-common (5.1.41-3ubuntu12.6) ...
Selecting previously deselected package mysql-server-5.1.
(Reading database ... 21101 files and directories currently installed.)
Unpacking mysql-server-5.1 (from .../mysql-server-5.1_5.1.41-3ubuntu12.6_amd64.deb) ...
Selecting previously deselected package libhtml-template-perl.
Unpacking libhtml-template-perl (from .../libhtml-template-perl_2.9-1_all.deb) ...
Selecting previously deselected package mysql-server.
Unpacking mysql-server (from .../mysql-server_5.1.41-3ubuntu12.6_all.deb) ...
Processing triggers for ureadahead ...
Processing triggers for man-db ...
Setting up libnet-daemon-perl (0.43-1) ...
Setting up libplrpc-perl (0.2020-2) ...
Setting up libdbi-perl (1.609-1build1) ...
Setting up libmysqlclient16 (5.1.41-3ubuntu12.6) ...
Setting up libdbd-mysql-perl (4.012-1ubuntu1) ...
Setting up mysql-client-core-5.1 (5.1.41-3ubuntu12.6) ...
Setting up mysql-client-5.1 (5.1.41-3ubuntu12.6) ...
Setting up mysql-server-core-5.1 (5.1.41-3ubuntu12.6) ...
Setting up mysql-server-5.1 (5.1.41-3ubuntu12.6) ...
mysql start/running, process 26154
Setting up libhtml-template-perl (2.9-1) ...
Setting up mysql-server (5.1.41-3ubuntu12.6) ...
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
Writing extended state information... Done
username@servername Tue Nov 02 22:09:21 ~/public_html/IDM_app
$ sudo aptitude install python-mysqldb
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
python-mysqldb python-support{a}
0 packages upgraded, 2 newly installed, 0 to remove and 44 not upgraded.
Need to get 0B/112kB of archives. After unpacking 504kB will be used.
Do you want to continue? [Y/n/?] y
Writing extended state information... Done
Selecting previously deselected package python-support.
(Reading database ... 21184 files and directories currently installed.)
Unpacking python-support (from .../python-support_1.0.4ubuntu1_all.deb) ...
Selecting previously deselected package python-mysqldb.
Unpacking python-mysqldb (from .../python-mysqldb_1.2.2-10build1_amd64.deb) ...
Processing triggers for man-db ...
Setting up python-support (1.0.4ubuntu1) ...
Setting up python-mysqldb (1.2.2-10build1) ...
Processing triggers for python-support ...
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
Writing extended state information... Done
username@servername Tue Nov 02 22:10:26 ~/public_html/IDM_app
$ python manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 13, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/__init__.py", line 67, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/contrib/contenttypes/generic.py", line 6, in <module>
from django.db import connection
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/__init__.py", line 77, in <module>
connection = connections[DEFAULT_DB_ALIAS]
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/utils.py", line 91, in __getitem__
backend = load_backend(db['ENGINE'])
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/utils.py", line 32, in load_backend
return import_module('.base', backend_name)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/backends/mysql/base.py", line 14, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
username@servername Wed Nov 03 03:24:00 ~/public_html/IDM_app
$ find / -name python-mysqldb 2>/dev/null
/usr/share/doc/python-mysqldb
username@servername Wed Nov 03 12:46:55 ~/public_html/IDM_app
$ ls /usr/local/mysql/bin/mysql_config
ls: cannot access /usr/local/mysql/bin/mysql_config: No such file or directory
username@servername Wed Nov 03 13:21:02 ~/public_html/IDM_app
$ find / -name mysql_config 2>/dev/null
username@servername Wed Nov 03 13:23:04 ~/public_html/IDM_app
$ find / -name python-mysqldb 2>/dev/null
/usr/share/doc/python-mysqldb
username@servername Wed Nov 03 13:29:01 ~/public_html/IDM_app
$ find / -name python-mysql 2>/dev/null
username@servername Wed Nov 03 13:29:21 ~/public_html/IDM_app
$ find / -name mysql 2>/dev/null
/etc/init.d/mysql
/etc/mysql
/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/contrib/gis/db/backends/mysql
/usr/local/lib/python2.7/site-packages/Django-1.2.3-py2.7.egg/django/db/backends/mysql
/usr/share/mysql
/usr/bin/mysql
/usr/lib/perl5/auto/DBD/mysql
/usr/lib/perl5/DBD/mysql
/usr/lib/mysql
/var/log/mysql
/var/lib/update-rc.d/mysql
/var/lib/mysql
username@servername Wed Nov 03 13:30:21 ~/public_html/IDM_app
$ ls -la /usr/bin/mysql
-rwxr-xr-x 1 root 183376 Jul 29 22:54 /usr/bin/mysql
username@servername Wed Nov 03 13:35:01 ~/public_html/IDM_app
$ find / -name site.cfg 2>/dev/null
username@servername Wed Nov 03 13:44:04 ~/public_html/IDM_app
$ ls -la /usr/lib/mysql/
total 16
drwxr-xr-x 3 root 4096 Nov 2 22:09 .
drwxr-xr-x 42 root 8192 Nov 2 22:10 ..
drwxr-xr-x 2 root 4096 Nov 2 22:09 plugin
| [
"The fix was:\nsudo aptitude install libmysqlclient-dev\n\nsudo easy_install MySQL-python \n\n",
"First, try dpkg -L python-mysqldb, then you'll see what's installed.\nSecond, you are obviously using a manully compiled Python 2.7, while Ubuntu installs its packages for Python 2.6, which is the current default. Yo... | [
2,
1
] | [] | [] | [
"aptitude",
"mysql",
"python"
] | stackoverflow_0004088397_aptitude_mysql_python.txt |
Q:
Use WTForms with webapp and Django templates on Google App Engine
I'm trying to use WTForms with webapp without much luck.
I would like to be able to use the form_field templatetag, as shown in the documentation:
{% form_field form.username class="big_text" onclick="do_something()" %}
I've got WTForms installed fine in my application, but its Django template tags isn't working for me. Does anyone have instructions on how to get this installed?
If I can't get this working, I will probably give up and switch to Jinja2 templates. The reason we have kept with Django so far is to limit the number of dependencies as much as possible.
Here's what I've tried so far:
I've install Django 1.1 locally and enabled it per the documentation.
I tried adding INSTALLED_APPS = ['wtforms.ext.django'] to my settings.py - no effect.
I tried registering the wtforms templatetag manually:.
register = webapp.template.create_template_register()
from wtforms.ext.django.templatetags import wtforms
register.tag('form_field', wtforms.do_form_field)
This gave me an error: InvalidTemplateLibrary: Could not load template library from template_helpers, No module named django.templatetags
So I tried copying and pasting the template tags into my own code, and I got the error TemplateSyntaxError: Could not parse the remainder: ' form.foobar' from 'form_field form.foobar.
However, I don't think the templatetag registration worked, because the error was the same without that code.
Update: I'm leaving this question up in case someone on the internet can some day answer it, but I switched to Jinja2 and now everything works perfectly. Webapp with Django templates is dead to me. ;-)
A:
I recommend jinja2 templates over django: http://jinja.pocoo.org/ It's based on the django templates but more powerful and easy to use. I don't think it's a good idea to use Django templates without the django stack. Also, if you want a more structured framework, a VERY nice minimalist framework is Flask: http://www.pocoo.org/projects/flask/#flask. I can't praise those two libraries enough. I worked a long time in Django and found this combo to be very refreshing and succinct.
P.S. this should be a very simple process to port over. It took me 10 minutes to port over a webapp site when I just found out about Flask.
| Use WTForms with webapp and Django templates on Google App Engine | I'm trying to use WTForms with webapp without much luck.
I would like to be able to use the form_field templatetag, as shown in the documentation:
{% form_field form.username class="big_text" onclick="do_something()" %}
I've got WTForms installed fine in my application, but its Django template tags isn't working for me. Does anyone have instructions on how to get this installed?
If I can't get this working, I will probably give up and switch to Jinja2 templates. The reason we have kept with Django so far is to limit the number of dependencies as much as possible.
Here's what I've tried so far:
I've install Django 1.1 locally and enabled it per the documentation.
I tried adding INSTALLED_APPS = ['wtforms.ext.django'] to my settings.py - no effect.
I tried registering the wtforms templatetag manually:.
register = webapp.template.create_template_register()
from wtforms.ext.django.templatetags import wtforms
register.tag('form_field', wtforms.do_form_field)
This gave me an error: InvalidTemplateLibrary: Could not load template library from template_helpers, No module named django.templatetags
So I tried copying and pasting the template tags into my own code, and I got the error TemplateSyntaxError: Could not parse the remainder: ' form.foobar' from 'form_field form.foobar.
However, I don't think the templatetag registration worked, because the error was the same without that code.
Update: I'm leaving this question up in case someone on the internet can some day answer it, but I switched to Jinja2 and now everything works perfectly. Webapp with Django templates is dead to me. ;-)
| [
"I recommend jinja2 templates over django: http://jinja.pocoo.org/ It's based on the django templates but more powerful and easy to use. I don't think it's a good idea to use Django templates without the django stack. Also, if you want a more structured framework, a VERY nice minimalist framework is Flask: http://w... | [
5
] | [] | [] | [
"django_templates",
"google_app_engine",
"python",
"wtforms"
] | stackoverflow_0004207590_django_templates_google_app_engine_python_wtforms.txt |
Q:
Parameterizing 'SELECT IN (...)' queries
I want to use MySQLdb to create a parameterized query such as:
serials = ['0123456', '0123457']
c.execute('''select * from table where key in %s''', (serials,))
But what ends up being send to the DBMS is:
select * from table where key in ("'0123456'", "'0123457'")
Is it possible to create a parameterized query like this? Or do I have to loop myself and build up a result set?
Note: executemany(...) won't work for this - it'll only return the last result:
>>> c.executemany('''select * from table where key in (%s)''',
[ (x,) for x in serials ] )
2L
>>> c.fetchall()
((1, '0123457', 'faketestdata'),)
Final solution adapted from Gareth's clever answer:
# Assume check above for case where len(serials) == 0
query = '''select * from table where key in ({0})'''.format(
','.join(["%s"] * len(serials)))
c.execute(query, tuple(serials)) # tuple() for case where len == 1
A:
You want something like this, I think:
query = 'select * from table where key in (%s)' % ','.join('?' * len(serials))
c.execute(query, serials)
| Parameterizing 'SELECT IN (...)' queries | I want to use MySQLdb to create a parameterized query such as:
serials = ['0123456', '0123457']
c.execute('''select * from table where key in %s''', (serials,))
But what ends up being send to the DBMS is:
select * from table where key in ("'0123456'", "'0123457'")
Is it possible to create a parameterized query like this? Or do I have to loop myself and build up a result set?
Note: executemany(...) won't work for this - it'll only return the last result:
>>> c.executemany('''select * from table where key in (%s)''',
[ (x,) for x in serials ] )
2L
>>> c.fetchall()
((1, '0123457', 'faketestdata'),)
Final solution adapted from Gareth's clever answer:
# Assume check above for case where len(serials) == 0
query = '''select * from table where key in ({0})'''.format(
','.join(["%s"] * len(serials)))
c.execute(query, tuple(serials)) # tuple() for case where len == 1
| [
"You want something like this, I think:\nquery = 'select * from table where key in (%s)' % ','.join('?' * len(serials))\nc.execute(query, serials)\n\n"
] | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004207787_mysql_python.txt |
Q:
Django settings based on IP or hostname
I'd like to have something in my settings like
if ip in DEV_IPS:
SOMESETTING = 'foo'
else:
SOMESETTING = 'bar'
Is there an easy way to get the ip or hostname - also - is this is a bad idea ?
A:
import socket
socket.gethostbyname(socket.gethostname())
However, I'd recommend against this and instead maintain multiple settings file for each environment you're working with.
settings/__init__.py
settings/qa.py
settings/production.py
__init__.py has all of your defaults. At the top of qa.py, and any other settings file, the first line has:
from settings import *
followed by any overrides needed for that particular environment.
A:
One method some shops use is to have an environment variable set on each machine. Maybe called "environment". In POSIX systems you can do something like ENVIRONMENT=production in the user's .profile file (this will be slightly different for each shell and OS). Then in settings.py you can do something like this:
import os
if os.environ['ENVIRONMENT'] == 'production':
# Production
DATABASE_ENGINE = 'mysql'
DATABASE_NAME = ....
else:
# Development
| Django settings based on IP or hostname | I'd like to have something in my settings like
if ip in DEV_IPS:
SOMESETTING = 'foo'
else:
SOMESETTING = 'bar'
Is there an easy way to get the ip or hostname - also - is this is a bad idea ?
| [
"import socket\nsocket.gethostbyname(socket.gethostname())\n\nHowever, I'd recommend against this and instead maintain multiple settings file for each environment you're working with.\nsettings/__init__.py\nsettings/qa.py \nsettings/production.py\n\n__init__.py has all of your defaults. At the top of qa.py, and an... | [
12,
3
] | [] | [] | [
"django",
"hostname",
"ip",
"python",
"settings"
] | stackoverflow_0004207762_django_hostname_ip_python_settings.txt |
Q:
Python - urllib2 timeout
I got something below is snippet of my code
opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler())
opener.addheaders = [('Accept-encoding', 'gzip')]
fetch_timeout = 12
self.response = opener.open(url, timeout=fetch_timeout)
however, it code still waits 60~ seconds before timing out...
Any clues?
A:
At a guess you probably need to set the socket timeout
import socket
default_timeout = 12
socket.setdefaulttimeout(default_timeout)
A:
Which version are you using. It was added in 2.6
Also the method is
urllib2.urlopen(url[, data][, timeout])
Can you try providing
self.response = opener.open(url, None, fetch_timeout)
Yeah for all others, you could still use socket module to set socket time out.
A:
Look at the OpenerDirector class and the urllib2.install_opener() method.
| Python - urllib2 timeout | I got something below is snippet of my code
opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler())
opener.addheaders = [('Accept-encoding', 'gzip')]
fetch_timeout = 12
self.response = opener.open(url, timeout=fetch_timeout)
however, it code still waits 60~ seconds before timing out...
Any clues?
| [
"At a guess you probably need to set the socket timeout\nimport socket\n\ndefault_timeout = 12\n\nsocket.setdefaulttimeout(default_timeout)\n\n",
"Which version are you using. It was added in 2.6\nAlso the method is \nurllib2.urlopen(url[, data][, timeout])\n\nCan you try providing \nself.response = opener.open(u... | [
3,
2,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004207983_python_urllib2.txt |
Q:
How can I send in-body images in a mail using python?
how can i send in-body attached images in a mail using python?
I found this: http://docs.python.org/library/email-examples.html but it has not an example with images.
Thanks!
A:
Take a look at the big example of "how to send the entire contents of a directory as an email message". The image in the file fp is converted into the message part msg here:
msg = MIMEImage(fp.read(), _subtype=subtype)
and then the message part is attached to the outer message here:
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
If you want the image to appear inline rather than as an attachment, you should set its Content-Disposition to inline instead of attachment.
(If you want to create HTML messages that display attached images, then you need to use the multipart/related MIME type defined in RFC 2387. Ask if you need help with this.)
A:
Attach the image and use html to display it. See the MIME example from your link for how to attach it. An <img> tag will do for display in most clients. Make sure you use the appropriate MIME type for html. Your link tells you how to do that too.
| How can I send in-body images in a mail using python? | how can i send in-body attached images in a mail using python?
I found this: http://docs.python.org/library/email-examples.html but it has not an example with images.
Thanks!
| [
"Take a look at the big example of \"how to send the entire contents of a directory as an email message\". The image in the file fp is converted into the message part msg here:\nmsg = MIMEImage(fp.read(), _subtype=subtype)\n\nand then the message part is attached to the outer message here:\nmsg.add_header('Content-... | [
2,
0
] | [] | [] | [
"attachment",
"email",
"image",
"python"
] | stackoverflow_0004208007_attachment_email_image_python.txt |
Q:
How are Google App Engine model classes stored?
I'm in doubt how the objects are stored. Say I have a class defined like:
class SomeEntity(db.Model):
some_number = db.IntegerProperty(required=True)
def calculate_something(self):
return self.some_number * 2
My guess is that the only thing stored in the data store is the name/value/type of some_number together with the fully qualified name of the class (SomeEntity). However I have not stumbled upon any information that confirms this.
1) Can anyone confirm this?
I would like to confirm that I can change (and add/remove) methods without somehow affecting the data is stored.
2) Furthermore, what happens to existing objects if I add a new property to the class (and what if that property has required=true)?
A:
Entities are stored in the datastore in a protobuf representation (including its key - which includes your App ID and the entity's Kind). The Life of a Datastore Write article talks more about the representation of entities and how they are written to the datastore. Check out the rest of the articles in this series for more detailed information.
1) Methods have no bearing on the data stored with your entity, so you can add/remove/change these without affecting the representation of your data.
2) The datastore is schemaless (unlike the typical SQL database). Changing your Model has no impact on the data in the datastore at all. When you retrieve an existing entity, if it is missing a required field then an error will be raised. Alternatively, if you don't make it required and provide a default, then the default will be used for the missing field.
If you need to migrate an old model to a new one, you might want to consider using the appengine-mapreduce library to iterate over all of your entities and migrate each one individually. Read more about schema migration here.
A:
They are stored as protocol buffers. You can read about some of the details in the "How Entities and Indexes are Stored" article.
You can see what is actually stored with:
db.model_to_protobuf(your_entity)
It is safe to add / remove methods, just be careful about overwriting built-in methods.
Include a default value if you add a property that is required. Existing entities will not be updated until you re-put the entity.
| How are Google App Engine model classes stored? | I'm in doubt how the objects are stored. Say I have a class defined like:
class SomeEntity(db.Model):
some_number = db.IntegerProperty(required=True)
def calculate_something(self):
return self.some_number * 2
My guess is that the only thing stored in the data store is the name/value/type of some_number together with the fully qualified name of the class (SomeEntity). However I have not stumbled upon any information that confirms this.
1) Can anyone confirm this?
I would like to confirm that I can change (and add/remove) methods without somehow affecting the data is stored.
2) Furthermore, what happens to existing objects if I add a new property to the class (and what if that property has required=true)?
| [
"Entities are stored in the datastore in a protobuf representation (including its key - which includes your App ID and the entity's Kind). The Life of a Datastore Write article talks more about the representation of entities and how they are written to the datastore. Check out the rest of the articles in this ser... | [
10,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004208103_google_app_engine_google_cloud_datastore_python.txt |
Q:
Please help me understand the output of this assertMultiLineEqual failure
This is the output from a failed assertMultiLineEqual:
- </group></row></resultset>+ </group></row></resultset>
? +
I have no idea what this means and why its complaining about it being different. My script generates an XML string and I want to compare it to the contents of an XML file. I took the exact string that is outputted and made it the file contents, and its complaining about this last line.
Suggestions?
A:
It looks like one of the strings ends with a newline character, and the other doesn't.
| Please help me understand the output of this assertMultiLineEqual failure | This is the output from a failed assertMultiLineEqual:
- </group></row></resultset>+ </group></row></resultset>
? +
I have no idea what this means and why its complaining about it being different. My script generates an XML string and I want to compare it to the contents of an XML file. I took the exact string that is outputted and made it the file contents, and its complaining about this last line.
Suggestions?
| [
"It looks like one of the strings ends with a newline character, and the other doesn't.\n"
] | [
2
] | [] | [] | [
"python",
"testing"
] | stackoverflow_0004208196_python_testing.txt |
Q:
Comparing sql values
I'm using sqlite with python. I'm implementing the POP3 protocol. I have a table
msg_id text
date text
from_sender text
subject text
body text
hashkey text
Now I need to check for duplicate messages by checking the message id of the message retrieved against the existing msg_id's in the table. I encrypted the msg_id using md5 and put it in the hashkey column. Whenever I retrieve mail, I hash the message id and check it with the table values. Heres what I do.
def check_duplicate(new):
conn = sql.connect("mail")
c = conn.cursor()
m = hashlib.md5()
m.update(new)
c.execute("select hashkey from mail")
for row in c:
if m.hexdigest() == row:
return 0
else:
continue
return 1
It just refuses to work correctly. I tried printing the row value, it shows it in unicode, thats where the problem lies as it cannot compare properly.
Is there a better way to do this, or to improve my method?
A:
Well, if your only problem is with the comparison, then you could try:
if m.hexdigest() == row[0]:
since row is a tuple and not a string, but your basic strategy seems wrong to me. You're retrieving the hashkey for every row from the database, and then doing your own search for the right one. Much better to make the database do the search for you. The database is likely to be better at searching (since it probably has an index on the hashkey field—you did create an index for this field, didn't you?) and it only has to send one result to you, saving time. So you could issue a query like this to determine if the message exists:
m.execute('select exists(select * from mail where hashkey=?)', m.hexdigest())
A final point of style: Python has True and False, so there's no need to use 1 and 0 for Booleans.
A:
Might be an idea to ask MySQL to search for the hash key:
select count(*) from mail where hashkey = 'TheHashKey'
A:
The main issue is that you're trying to compare a Python string (m.hexdigest()) with a tuple.
Additionally, another poster's suggestion that you use SQL for the comparison is probably good advice. Another SQL suggestion would be to fix your columns -- TEXT for everything probably isn't what you want; an index on your hashkey column is very likely a good thing.
| Comparing sql values | I'm using sqlite with python. I'm implementing the POP3 protocol. I have a table
msg_id text
date text
from_sender text
subject text
body text
hashkey text
Now I need to check for duplicate messages by checking the message id of the message retrieved against the existing msg_id's in the table. I encrypted the msg_id using md5 and put it in the hashkey column. Whenever I retrieve mail, I hash the message id and check it with the table values. Heres what I do.
def check_duplicate(new):
conn = sql.connect("mail")
c = conn.cursor()
m = hashlib.md5()
m.update(new)
c.execute("select hashkey from mail")
for row in c:
if m.hexdigest() == row:
return 0
else:
continue
return 1
It just refuses to work correctly. I tried printing the row value, it shows it in unicode, thats where the problem lies as it cannot compare properly.
Is there a better way to do this, or to improve my method?
| [
"Well, if your only problem is with the comparison, then you could try:\nif m.hexdigest() == row[0]:\n\nsince row is a tuple and not a string, but your basic strategy seems wrong to me. You're retrieving the hashkey for every row from the database, and then doing your own search for the right one. Much better to ma... | [
4,
0,
0
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0004208146_python_sql_sqlite.txt |
Q:
What is the benefit of using the ConfigParser instead of a regular python.py file when writing configuration files?
I have been using the ConfigParser module to write configuration files for some time. However, a thought recently struck me; why not just use pure Python instead? Take this example configuration file:
[parameters]
# Host
host = stackoverflow.com
port = 22
To read these values into my code, I do
import ConfigParser
config = ConfigParser.SafeConfigParser()
config.read('host.cfg')
host = config.get('parameters', 'host')
port = config.get('parameters', 'port')
On the other hand, if I had a config file like this:
# Host
host = 'stackoverflow.com'
port = 22
In my main code, I could do this:
from host_cfg import *
So what do I gain from using the ConfigParser module? What are the pros and cons of each approach?
A:
So what do I gain from using the ConfigParser module?
Compatibility with Windows .ini files. Makes some people happy.
What are the pros and cons of each approach?
ConfigParser has limited syntax and some relatively simple things get very contrived. Look at logging for examples.
Python syntax is simpler and much easier to work with. There's no security hole, since no one will waste time hacking a config file when they can simply hack your source code. Indeed, they can hack most of the built-in Python library. For that matter, they could cook the Python interpreter itself.
No one wastes time hacking config files when there are much, much easier exploits elsewhere in your application source code.
A:
ConfigParser parses simple, flat configuration data. Importing a python module runs code. For configuration files, you want data, not code. Case closed.
Okay, more detailed: Code can do all kinds of things, including breaking more easily - especially when edited by non-programmers (try explaining .ini modders that they e.g. have to use matched quotes and escape things...) - or cause namespace conflicts with other parts of your application (especially if you import *). Also see the rule of Least Power.
A:
A potential "con" of the Python file approach is that your user can put arbitrary code in the file that will be executed in your application's context. As S. Lott points out in the comments to this answer (when I was somewhat more forceful in my warning), this is usually not an issue because the user (or a hacker) will usually have access to your entire source code anyway and can make any desired changes.
However, I can certainly imagine situations in which the approach could result in a new security hole, such as when the main script files are writable only by the system administrator and the per-user config file is the only file editable by the end user. Unless you are certain that your code will never run in such an environment, I would not recommend the Python module approach. There are good reasons that "don't execute code given to you by users" is widely considered a best practice.
Executing the config file also makes handling errors problematic. If the user introduces a syntax error, you will want to trap it, and you can do so easily by throwing a try around your import, but nothing after the error will be executed. In a config file, usually parsing will continue with the next line, so the user will miss at most one setting instead of (say) half of them. There are ways to make a Python module work more like a config file (you could read the file as text and exec() each line, for example) but if you have to do any work at all, it becomes easier to use ConfigParser.
If, despite all this, you still want to use Python syntax in your config file, you could use the ast module (see function literal_eval()).
| What is the benefit of using the ConfigParser instead of a regular python.py file when writing configuration files? | I have been using the ConfigParser module to write configuration files for some time. However, a thought recently struck me; why not just use pure Python instead? Take this example configuration file:
[parameters]
# Host
host = stackoverflow.com
port = 22
To read these values into my code, I do
import ConfigParser
config = ConfigParser.SafeConfigParser()
config.read('host.cfg')
host = config.get('parameters', 'host')
port = config.get('parameters', 'port')
On the other hand, if I had a config file like this:
# Host
host = 'stackoverflow.com'
port = 22
In my main code, I could do this:
from host_cfg import *
So what do I gain from using the ConfigParser module? What are the pros and cons of each approach?
| [
"\nSo what do I gain from using the ConfigParser module?\n\nCompatibility with Windows .ini files. Makes some people happy.\n\nWhat are the pros and cons of each approach?\n\nConfigParser has limited syntax and some relatively simple things get very contrived. Look at logging for examples.\nPython syntax is simpl... | [
11,
6,
4
] | [] | [] | [
"configuration",
"configuration_files",
"module",
"python"
] | stackoverflow_0004208323_configuration_configuration_files_module_python.txt |
Q:
How to make python module installer for windows?
How to make python module installer for windows?
I have python (2.7 if that makes difference) module which wrapped functionality around C-lib and would like to make an installer with build lib to make installation easy.
A:
Using distutils, you can write a setup file that would compile your libs and install them
http://docs.python.org/library/distutils.html
http://docs.python.org/distutils/index.html#distutils-index
See this example setup.py which also compiles "c" lib for different platforms.
http://code.google.com/p/psutil/source/browse/trunk/setup.py
| How to make python module installer for windows? | How to make python module installer for windows?
I have python (2.7 if that makes difference) module which wrapped functionality around C-lib and would like to make an installer with build lib to make installation easy.
| [
"Using distutils, you can write a setup file that would compile your libs and install them\n\nhttp://docs.python.org/library/distutils.html\nhttp://docs.python.org/distutils/index.html#distutils-index\n\nSee this example setup.py which also compiles \"c\" lib for different platforms.\n\nhttp://code.google.com/p/psu... | [
4
] | [] | [] | [
"installation",
"python",
"windows"
] | stackoverflow_0004208532_installation_python_windows.txt |
Q:
Alternative to singleton?
I'm a Python & App Engine (and server-side!) newbie, and I'm trying to create very simple CMS. Each deployment of the application would have one -and only one -company object, instantiated from something like:
class Company(db.Model):
name = db.StringPropery()
profile = db.TextProperty()
addr = db.TextProperty()
I'm trying to provide the facility to update the company profile and other details.
My first thought was to have a Company entity singleton. But having looked at (although far from totally grasped) this thread I get the impression that it's difficult, and inadvisable, to do this.
So then I thought that perhaps for each deployment of the CMS I could, as a one-off, run a script (triggered by a totally obscure URL) which simply instantiates Company. From then on, I would get this instance with theCompany = Company.all()[0]
Is this advisable?
Then I remembered that someone in that thread suggested simply using a module. So I just created a Company.py file and stuck a few variables in it. I've tried this in the SDK and it seems to work -to my suprise, modified variable values "survived" between requests.
Forgive my ignorance but, I assume these values are only held in memory rather than on disk -unlike Datastore stuff? Is this a robust solution? (And would the module variables be in scope for all invocations of my application's scripts?)
A:
Global variables are "app-cached." This means that each particular instance of your app will remember these variables' values between requests. However, when an instance is shutdown these values will be lost. Thus I do not think you really want to store these values in module-level variables (unless they are constants which do not need to be updated).
I think your original solution will work fine. You could even create the original entity using the remote API tool so that you don't need an obscure page to instantiate the one and only Company object.
You can also make the retrieval of the singleton Company entity a bit faster if you retrieve it by key.
If you will need to retrieve this entity frequently, then you can avoid round-trips to the datastore by using a caching technique. The fastest would be to app-cache the Company entity after you've retrieved it from the datastore. To protect against the entity from becoming too out of date, you can also app-cache the time you last retrieved the entity and if that time is more than N seconds old then you could re-fetch it from the datastore. For more details on this option and how it compares to alternatives, check out Nick Johnson's article Storage options on App Engine.
A:
It sounds like you are trying to provide a way for your app to be configurable on a per-application basis.
Why not use the datastore to store your company entity with a key_name? Then you will always know how to fetch the company entity, and you'll be able edit the company without redeploying.
company = Company(key_name='c')
# set stuff on company....
company.put()
# later in code...
company = Company.get_by_key_name('c')
Use memcache to store the details of the company and avoid repeated datastore calls.
In addition to memcache, you can use module variables to cache the values. They are cached, as you have seen, between requests.
A:
I think the approach you read about is the simplest:
Use module variables, initialized in None.
Provide accessors (get/setters) for these variables.
When a variable is accessed, if its value is None, fetch it from the database. Otherwise, just use it.
This way, you'll have app-wide variables provided by the module (which won't be instantiated again and again), they will be shared and you won't lose them.
| Alternative to singleton? | I'm a Python & App Engine (and server-side!) newbie, and I'm trying to create very simple CMS. Each deployment of the application would have one -and only one -company object, instantiated from something like:
class Company(db.Model):
name = db.StringPropery()
profile = db.TextProperty()
addr = db.TextProperty()
I'm trying to provide the facility to update the company profile and other details.
My first thought was to have a Company entity singleton. But having looked at (although far from totally grasped) this thread I get the impression that it's difficult, and inadvisable, to do this.
So then I thought that perhaps for each deployment of the CMS I could, as a one-off, run a script (triggered by a totally obscure URL) which simply instantiates Company. From then on, I would get this instance with theCompany = Company.all()[0]
Is this advisable?
Then I remembered that someone in that thread suggested simply using a module. So I just created a Company.py file and stuck a few variables in it. I've tried this in the SDK and it seems to work -to my suprise, modified variable values "survived" between requests.
Forgive my ignorance but, I assume these values are only held in memory rather than on disk -unlike Datastore stuff? Is this a robust solution? (And would the module variables be in scope for all invocations of my application's scripts?)
| [
"Global variables are \"app-cached.\" This means that each particular instance of your app will remember these variables' values between requests. However, when an instance is shutdown these values will be lost. Thus I do not think you really want to store these values in module-level variables (unless they are ... | [
2,
2,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004208390_google_app_engine_google_cloud_datastore_python.txt |
Q:
Executing several Python scripts at same time causes PHP/Apache to hang
I'm trying to execute a few python scripts in order to manipulate some images on my website. The external program/tool is written in python and is called PHATCH. I'm under Windows and using WAMP as my web server.
Executing only just one script seems to work well, but I need to execute 4 scripts at the same time (to generate 4 different images), my browser will just load and Apache/PHP freezes.
The PHP execution seems to freeze and hung up due several system() calls after each other. Here's an example of how I'm using it:
system("C:\\python\\python.exe C:\\phatch\\phatch.py script1.phatch");
system("C:\\python\\python.exe C:\\phatch\\phatch.py script2.phatch");
system("C:\\python\\python.exe C:\\phatch\\phatch.py script3.phatch");
system("C:\\python\\python.exe C:\\phatch\\phatch.py script4.phatch");
If I only do the first one, it's fine, but as soon as I add the others, it all freezes.
A:
Can multiple copies of phatch be executed simultaneously from the same account? Have you tried this without PHP and Apache?
it is possible that multiple copies starting at the same time access the same files, perhaps use the same temporary files (even with unique names, if the name is based on time, they might have the same name...)
| Executing several Python scripts at same time causes PHP/Apache to hang | I'm trying to execute a few python scripts in order to manipulate some images on my website. The external program/tool is written in python and is called PHATCH. I'm under Windows and using WAMP as my web server.
Executing only just one script seems to work well, but I need to execute 4 scripts at the same time (to generate 4 different images), my browser will just load and Apache/PHP freezes.
The PHP execution seems to freeze and hung up due several system() calls after each other. Here's an example of how I'm using it:
system("C:\\python\\python.exe C:\\phatch\\phatch.py script1.phatch");
system("C:\\python\\python.exe C:\\phatch\\phatch.py script2.phatch");
system("C:\\python\\python.exe C:\\phatch\\phatch.py script3.phatch");
system("C:\\python\\python.exe C:\\phatch\\phatch.py script4.phatch");
If I only do the first one, it's fine, but as soon as I add the others, it all freezes.
| [
"Can multiple copies of phatch be executed simultaneously from the same account? Have you tried this without PHP and Apache?\nit is possible that multiple copies starting at the same time access the same files, perhaps use the same temporary files (even with unique names, if the name is based on time, they might ha... | [
0
] | [] | [] | [
"exec",
"php",
"python",
"system"
] | stackoverflow_0004208573_exec_php_python_system.txt |
Q:
Python: Write a program to find the time period(s) of the largest price drop(s)
i am suppose to solve this question but i am stuck.
Write a program to find the time period(s) of the largest price drop(s) when a list of price(s) is given. For instance, if the list is [300,301,303,299,300,298,301,305], then there is one period of the largest price drop: from time 2 with price 303 to time 5 with price 298.
Below is my solution but there is a flaw
def maxdrop(p):
high = low = drop = newhigh = 0
for i in range(len(p)):
if p[i] >= p[high]:
newhigh = i # invariant: p[high] <= p[newhigh]
else: # so: p[i] < p[high] <= p[newhigh]
newdrop = p[newhigh] - p[i]
if newdrop >= drop:
high, low, drop = newhigh, i, newdrop
return ((high, p[high]), (low, p[low]), drop)
def test():
p = [20,22,19,20,24,18,21,24,27]
print p, maxdrop(p)
p = list(reversed(p))
print p, maxdrop(p)
if __name__ == "__main__":
test()
If you try with the below list
[2,1,2,3,4,3,2]
the sharpest drop should occurs over 4,3,2 – the last 3 elements.
But with my code, the output is 2,1 – the first 2 elements.
Please assist, thanks!
A:
You want the maximum sum contiguous sequence, but inverted. This page has the best explanation of it I have seen.
The basic algorithm will look like this:
>>> def min_sum_subsequence(seq):
... minsofar = 0
... minendinghere = 0
... for s in seq:
... # invariant: maxendinghere and maxsofar are accurate
... # are accurate up to s
... minendinghere = min(minendinghere + s, 0)
... minsofar = min(minsofar, minendinghere)
... return minsofar
...
>>> series = [300,301,303,299,300,298,301,305]
>>> returns = [series[i] - series[i-1] for i in range(1, len(series))]
>>> min_sum_subsequence(returns)
-5
You have to add code to keep track of the index of the start and finish.
A:
Its always best to print all the values and check out the results.
The problem with your code is when you write p[i]> p[high] you update the value of newhigh but the value of high is not changing.
Just write it as p[i] > p[newhigh] and check out if its giving the correct results. I have'nt checked if it will give the correct output. Do that on your own.
Though you can always use the shortened versions mentioned above.
A:
Python allows for much shorter code:
l = [300,301,303,299,300,298,301,305]
max([(l[i] - l[j], i, j) for i in range(len(l)) for j in range(i, len(l))], key=lambda x:x[0])
(5, 2, 5)
This can maybe be shortened, but it's a good starting point.
Also, as others said, please use [homework] tag if appropriate.
Edit: this answers (drop, begin, end).
A:
Having copy-pasted your code and indented it, you're nearly there. Where you test:
if p[i] >= p[high]:
You're not considering that p[i] might be >= p[high], but less than p[newhigh].
A:
You are asking for the largest non-monotonically decreasing sequence. There is a similar question for monotonically in this question. Lots of ways to approach this problem. Here is a recursive approach.
def biggest_drop(sequence):
seq_min, seq_max = min(sequence), max(sequence)
imin, imax = sequence.index(seq_min), sequence.index(seq_max)
if imin == imax:
return None
if imin < imax:
# split the sequence and look for local drops
drop_a = biggest_drop(sequence[:imax])
drop_b = biggest_drop(sequence[imax:])
if drop_a is None or drop_b is None:
if drop_a:
return drop_a
return drop_b
value_a = drop_a[0] - drop_a[-1]
value_b = drop_b[0] - drop_b[-1]
if value_a > value_b:
return drop_a
else:
return drop_b
return sequence[imax:imin+1]
A:
Here is my solution:
start_=stop_=None
min_=0
for start in range(len(li)-1):
for stop in range(start+1, len(li)):
tmp= li[stop]-li[start]
if tmp<min_:
min_=tmp
start_=start
stop_=stop
print min_
print (start_, stop_)
It works for your sample.
A:
Here's my try at it. It works correctly on all the examples that you gave.
I basically just go through the array and when there is a drop between two points, referring to the first point as A, look ahead until there is a value that is higher than A. I keep track of the minimum in this region. If the difference between A and the minimum is a bigger drop than what I've already found, I hold onto it. I then start looking again for a drop between two points, starting at the next point that was higher than A.
Here's the code. It isn't very Python-esque, but it works pretty well (I'd just go to Cython if I needed it to be faster). Also, it returns the magnitude of the drop.
def maxdrop(p):
bestdrop = 0
wheredrop = -1,-1
i = 0
while i < len(p) - 1:
if p[i+1] < p[i]:
bestlocal = p[i+1]
wherelocal = i+1
j = i + 1
while j < len(p) - 1 and p[j + 1] < p[i]:
j += 1
if p[j] < bestlocal:
bestlocal = p[j]
wherelocal = j
if p[i] - bestlocal > bestdrop:
bestdrop = p[i] - bestlocal
wheredrop = i, wherelocal
i = j+1
else:
i += 1
return bestdrop,wheredrop
A big problem with your code is that you only look at the next value for the biggest drop after a new high value is found.
A:
There's a faster way to compute mins than this example, but this is concise and readable:
>>> data = [300, 301, 303, 299, 300, 298, 301, 305]
>>> mins = [min(data[i:]) for (i, _) in enumerate(data)]
>>> mins
[298, 298, 298, 298, 298, 298, 301, 305]
>>> drops = [ d - m for (d, m) in zip(data, mins)]
>>> drops
[2, 3, 5, 1, 2, 0, 0, 0]
>>> [ (i, data[i] - drop) for (i, drop) in enumerate(drops) if drop == max(drops) ]
[(2, 298)]
Knowing that the start of the period is 2 and the low point is 298, the end of the period is:
>>> [ i for (i, x) in enumerate(data) if i > 2 and x == 298]
[5]
| Python: Write a program to find the time period(s) of the largest price drop(s) | i am suppose to solve this question but i am stuck.
Write a program to find the time period(s) of the largest price drop(s) when a list of price(s) is given. For instance, if the list is [300,301,303,299,300,298,301,305], then there is one period of the largest price drop: from time 2 with price 303 to time 5 with price 298.
Below is my solution but there is a flaw
def maxdrop(p):
high = low = drop = newhigh = 0
for i in range(len(p)):
if p[i] >= p[high]:
newhigh = i # invariant: p[high] <= p[newhigh]
else: # so: p[i] < p[high] <= p[newhigh]
newdrop = p[newhigh] - p[i]
if newdrop >= drop:
high, low, drop = newhigh, i, newdrop
return ((high, p[high]), (low, p[low]), drop)
def test():
p = [20,22,19,20,24,18,21,24,27]
print p, maxdrop(p)
p = list(reversed(p))
print p, maxdrop(p)
if __name__ == "__main__":
test()
If you try with the below list
[2,1,2,3,4,3,2]
the sharpest drop should occurs over 4,3,2 – the last 3 elements.
But with my code, the output is 2,1 – the first 2 elements.
Please assist, thanks!
| [
"You want the maximum sum contiguous sequence, but inverted. This page has the best explanation of it I have seen.\nThe basic algorithm will look like this:\n>>> def min_sum_subsequence(seq):\n... minsofar = 0\n... minendinghere = 0\n... for s in seq:\n... # invariant: maxendinghere and maxsofar... | [
5,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004204807_python.txt |
Q:
Help needed to convert code from C# to Python
Can you please convert this code from C# to Python to be run on IronPython?
I don’t have any experience with Python.
using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
Agent bar = new Agent("Bar");
foo.Connect("127.0.0.1", 1234);
foo.Add(bar);
bar.Ready += new Agent.ReadyHandler(bar_Ready);
}
static void bar_Ready(object sender, string msg)
{
Console.WriteLine(msg.body);
}
}
}
A:
Instantiation doesn't require a type definition. Methods called the same, assign delegates directly. The previous answer is absolutely right, you'll need a lot more context in order to "convert" a C# application to Python; it's more than just syntax.
foo = Portal("Foo")
bar = Agent("bar")
foo.Connect("ip", 1234)
foo.Add(bar)
bar.Ready = bar_Ready
def bar_Ready(sender, msg):
print msg.body
A:
I think it would suit you best if you take a look at the following links:
http://www.learningpython.com/2006/10/02/ironpython-hello-world-tutorial/
http://msdn.microsoft.com/en-us/magazine/cc300810.aspx
A:
Or if you're feeling really lazy, there's a C# to Python converter on developer fusion!
| Help needed to convert code from C# to Python | Can you please convert this code from C# to Python to be run on IronPython?
I don’t have any experience with Python.
using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
Agent bar = new Agent("Bar");
foo.Connect("127.0.0.1", 1234);
foo.Add(bar);
bar.Ready += new Agent.ReadyHandler(bar_Ready);
}
static void bar_Ready(object sender, string msg)
{
Console.WriteLine(msg.body);
}
}
}
| [
"Instantiation doesn't require a type definition. Methods called the same, assign delegates directly. The previous answer is absolutely right, you'll need a lot more context in order to \"convert\" a C# application to Python; it's more than just syntax.\nfoo = Portal(\"Foo\")\n\nbar = Agent(\"bar\")\n\nfoo.Connect(... | [
5,
2,
2
] | [
"In case someone else has this question SharpDevelop has a conversion utility to convert between C# and IronPython, VB.NET or Boo\nhttp://community.sharpdevelop.net/blogs/mattward/archive/2009/05/11/ConvertingCSharpVBNetCodeToIronPython.aspx\n"
] | [
-1
] | [
".net",
"c#",
"ironpython",
"python"
] | stackoverflow_0000542908_.net_c#_ironpython_python.txt |
Q:
When to use sys.path.append and when modifying %PYTHONPATH% is enough
So, it turned out i was missing a semi-colon from my PYTHONPATH definition. But this only got me so far. for some reason, my script did NOT work as a scheduled task (on WinXP) until I explicitly added a directory from PYTHONPATH to the top of my script.
Question is:
When do I need to explicitly append something to my path and when can I simply rely on the environment variables?
A:
Perhaps you're not running the scheduled task under the right credentials (log-in name). When you define environment variables in System Properties dialog, they can be either User-level or System-level. If you defined PYTHONPATH as User-level then your scheduled task must run as that user for it to be set properly. I believe making it System-level would mean it would apply to all users unless they have their own value defined.
Below is a screenshot showing where one sets environment variables. It's similar in both Windows XP and Windows 7. The top half of the right-hand dialog box shows the current User-level settings, and the bottom half lists all the System-level ones.
If PYTHONPATH appears in the list of names in the upper User-level group, you can effectively move it to the other lower one by first deleting and then adding one of the same name plus associated value to the lower System-level set. To save a little typing, you can Edit the user-level variable before you Delete it to be given a chance to first copy its current value, then Cancel-out of the operation. That way, when you make the New System-level copy you'll be able to simply paste the copied value into it.
A:
If the other modules belongs to the same package you should be responsible to locate them if
they are not stored in the conventional format (i.e. append the path with sys).
If the other modules are user-configurable then the user have to specify the installation
path trough PYTHONPATH
| When to use sys.path.append and when modifying %PYTHONPATH% is enough | So, it turned out i was missing a semi-colon from my PYTHONPATH definition. But this only got me so far. for some reason, my script did NOT work as a scheduled task (on WinXP) until I explicitly added a directory from PYTHONPATH to the top of my script.
Question is:
When do I need to explicitly append something to my path and when can I simply rely on the environment variables?
| [
"Perhaps you're not running the scheduled task under the right credentials (log-in name). When you define environment variables in System Properties dialog, they can be either User-level or System-level. If you defined PYTHONPATH as User-level then your scheduled task must run as that user for it to be set properly... | [
4,
0
] | [] | [] | [
"environment_variables",
"python"
] | stackoverflow_0004208659_environment_variables_python.txt |
Q:
importing from higher directories in python
Possible Duplicate:
How to do relative imports in Python?
How do I import from a higher level directory in python.
For example:
I have project/lib/lib.py
project/stuff/main.py
i want to import lib.py in main.py
Thanks in advance
A:
You can do it like:
from ..lib import lib
A:
standard method is to add project to your path and do
import lib.lib
You will need a file called __init__.py in the lib folder as well, which can be blank.
| importing from higher directories in python |
Possible Duplicate:
How to do relative imports in Python?
How do I import from a higher level directory in python.
For example:
I have project/lib/lib.py
project/stuff/main.py
i want to import lib.py in main.py
Thanks in advance
| [
"You can do it like:\nfrom ..lib import lib\n\n",
"standard method is to add project to your path and do\nimport lib.lib\n\nYou will need a file called __init__.py in the lib folder as well, which can be blank.\n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004209214_python.txt |
Q:
Django: Having unique extension numbers associated with a client, but same extension number associated with another client
I'm working on a project where I have models: Client, User, and Extensions, just to make this simple.
A User has to be associated with one Client in order to have an Extension number.
A User can have extensions, say, 100 and 101.
Another User, associated with another Client, can have the same extensions 100 and 101.
So, Extensions is not unique in my database so it's allowing a User to have two identical extension numbers when I add it in the Administration, which is wrong. How can check that the extension number to be added is not contained in this user already?
class Extension(models.Model):
user = models.ForeignKey(User, verbose_name=u"User")
date_created = models.DateTimeField(auto_now_add=True, auto_now=True)
number = models.CharField(max_length=16, unique=False)
kind = models.SmallIntegerField(choices=KIND_CHOICES,default=KIND_UNKNOWN)
The User class is the default Django class.
class Client(models.Model):
name = models.CharField(u"Nome", max_length=64)
last_update = models.DateTimeField(null=True, blank=True)
last_inbound_call = models.DateTimeField(null=True, blank=True)
last_outbound_call = models.DateTimeField(null=True, blank=True)
username = models.CharField(max_length=32)
password = models.CharField(max_length=16)
A:
Use Meta.unique_together on user and number in Extension.
class Extension(...):
...
class Meta:
unique_together = (('user', 'number'),)
| Django: Having unique extension numbers associated with a client, but same extension number associated with another client | I'm working on a project where I have models: Client, User, and Extensions, just to make this simple.
A User has to be associated with one Client in order to have an Extension number.
A User can have extensions, say, 100 and 101.
Another User, associated with another Client, can have the same extensions 100 and 101.
So, Extensions is not unique in my database so it's allowing a User to have two identical extension numbers when I add it in the Administration, which is wrong. How can check that the extension number to be added is not contained in this user already?
class Extension(models.Model):
user = models.ForeignKey(User, verbose_name=u"User")
date_created = models.DateTimeField(auto_now_add=True, auto_now=True)
number = models.CharField(max_length=16, unique=False)
kind = models.SmallIntegerField(choices=KIND_CHOICES,default=KIND_UNKNOWN)
The User class is the default Django class.
class Client(models.Model):
name = models.CharField(u"Nome", max_length=64)
last_update = models.DateTimeField(null=True, blank=True)
last_inbound_call = models.DateTimeField(null=True, blank=True)
last_outbound_call = models.DateTimeField(null=True, blank=True)
username = models.CharField(max_length=32)
password = models.CharField(max_length=16)
| [
"Use Meta.unique_together on user and number in Extension.\nclass Extension(...):\n ...\n class Meta:\n unique_together = (('user', 'number'),)\n\n"
] | [
5
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004209345_django_django_admin_django_models_python.txt |
Q:
How to raise a 410 error in Django
I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling raise Http404('some error message'), I would like to instead call raise Http410('some error message') shortcut.
I am confused because in django.http, the function Http404 is simply:
class Http404(Exception):
pass
So if I do the same thing and create my Http410 function, I would assume it would look like:
class Http410(Exception):
pass
However, doing this returns the exception but serves up a 500 error page. How do I recreate the magic of the Http404 exception? I should note, I need to raise the exception from my models (not views) so I can't just return an HttpResponseGone.
Thanks in advance!
Update:
I am fully aware of HttpResponseGone and mentioned this in my original question. I already know how to return this in my views. My question is: How do you raise an Http 410 exception similarly to how you raise an Http 404 exception? I want to be able to raise this exception anywhere, not just in my views. Thanks!
A:
from django.http import HttpResponse
return HttpResponse(status=410)
A:
Django does not include a mechanism for this because gone should be normal workflow, not an error condition, but if you want to not treat it as a return response, and as an exception, just implement a middleware.
class MyGoneMiddleware(object):
def process_exception(self, request, exception):
if isinstance(exception, Http410):
return HttpResponseGone("Gone!")
return None
A:
Return a HttpResponseGone, a subclass of HttpResponse, in your view handler.
| How to raise a 410 error in Django | I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling raise Http404('some error message'), I would like to instead call raise Http410('some error message') shortcut.
I am confused because in django.http, the function Http404 is simply:
class Http404(Exception):
pass
So if I do the same thing and create my Http410 function, I would assume it would look like:
class Http410(Exception):
pass
However, doing this returns the exception but serves up a 500 error page. How do I recreate the magic of the Http404 exception? I should note, I need to raise the exception from my models (not views) so I can't just return an HttpResponseGone.
Thanks in advance!
Update:
I am fully aware of HttpResponseGone and mentioned this in my original question. I already know how to return this in my views. My question is: How do you raise an Http 410 exception similarly to how you raise an Http 404 exception? I want to be able to raise this exception anywhere, not just in my views. Thanks!
| [
"from django.http import HttpResponse\nreturn HttpResponse(status=410)\n\n",
"Django does not include a mechanism for this because gone should be normal workflow, not an error condition, but if you want to not treat it as a return response, and as an exception, just implement a middleware.\nclass MyGoneMiddleware... | [
24,
16,
11
] | [] | [] | [
"django",
"error_handling",
"http_status_code_410",
"httpresponse",
"python"
] | stackoverflow_0004208572_django_error_handling_http_status_code_410_httpresponse_python.txt |
Q:
Why do I get PROCEDURE does not exist when using callproc() in Django?
So I'm trying to use a stored procedure via a cursor and callproc() but I always get the error:
OperationalError: (1305, 'PROCEDURE myapp.LatLonDistance does not exist')
Here's the chunk of code that throws the error in my app:
cursor = connection.cursor()
result = cursor.callproc("myapp.LatLonDistance", (lat1, lon1, lat2, lon2))
cursor.close()
And here's a direct query that I can run on the DB that works just fine:
SELECT id,myapp.LatLonDistance(lat1, lon1, lat2, lon2) AS distance FROM myapp.users_userprofile;
And here's the script I use to write the stored procedure to the DB:
delimiter //
CREATE FUNCTION airrun.LatLonDistance (lat1 double, lon1 double, lat2 double, lon2 double)
RETURNS double
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE theta double;
DECLARE dist double;
DECLARE miles double;
SET theta = lon1 - lon2;
SET dist = SIN(RADIANS(lat1)) * SIN(RADIANS(lat2)) + COS(RADIANS(lat1)) * COS(RADIANS(lat2)) * COS(RADIANS(theta));
SET dist = ACOS(dist);
SET dist = DEGREES(dist);
SET miles = dist * 60 * 1.1515;
RETURN miles;
END
//
delimiter ;
Using a MySQL db. Any thoughts?
A:
Since that is a function, and not actually a stored procedure, you should be able to call it using cursor.execute:
cursor = connection.cursor()
result = cursor.execute("SELECT id,myapp.LatLonDistance(%s, %s, %s, %s) AS distance FROM myapp.users_userprofile", (lat1, lon1, lat2, lon2))
cursor.close()
| Why do I get PROCEDURE does not exist when using callproc() in Django? | So I'm trying to use a stored procedure via a cursor and callproc() but I always get the error:
OperationalError: (1305, 'PROCEDURE myapp.LatLonDistance does not exist')
Here's the chunk of code that throws the error in my app:
cursor = connection.cursor()
result = cursor.callproc("myapp.LatLonDistance", (lat1, lon1, lat2, lon2))
cursor.close()
And here's a direct query that I can run on the DB that works just fine:
SELECT id,myapp.LatLonDistance(lat1, lon1, lat2, lon2) AS distance FROM myapp.users_userprofile;
And here's the script I use to write the stored procedure to the DB:
delimiter //
CREATE FUNCTION airrun.LatLonDistance (lat1 double, lon1 double, lat2 double, lon2 double)
RETURNS double
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE theta double;
DECLARE dist double;
DECLARE miles double;
SET theta = lon1 - lon2;
SET dist = SIN(RADIANS(lat1)) * SIN(RADIANS(lat2)) + COS(RADIANS(lat1)) * COS(RADIANS(lat2)) * COS(RADIANS(theta));
SET dist = ACOS(dist);
SET dist = DEGREES(dist);
SET miles = dist * 60 * 1.1515;
RETURN miles;
END
//
delimiter ;
Using a MySQL db. Any thoughts?
| [
"Since that is a function, and not actually a stored procedure, you should be able to call it using cursor.execute:\ncursor = connection.cursor()\nresult = cursor.execute(\"SELECT id,myapp.LatLonDistance(%s, %s, %s, %s) AS distance FROM myapp.users_userprofile\", (lat1, lon1, lat2, lon2))\ncursor.close()\n\n"
] | [
3
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0004208807_django_mysql_python.txt |
Q:
tkinter python: How do remove the input cursor from a ttk.Entry?
I have an instance of ttk.Entry.
The user clicks it.
I have the event bound.
Depending on some condition, I either want the input cursor to appear and allow typing or I essentially want to ignore the click and not have the input cursor appear in the ttk.Entry. I don't want to have to use the readonly or disabled states.
Manipulating focus has not effect.
A:
Here is a class that does what you ask.
class MyEntry(Entry):
def disable(self):
self.__old_insertontime = self.cget('insertontime')
self.config(insertontime=0)
self.bind('<Key>', lambda e: 'break')
def enable(self):
self.unbind('<Key>')
if self.cget('insertontime') == 0:
self.config(insertontime=self.__old_insertontime)
However, since your real concern is that you don't want a disabled Entry to look disabled, just set the colors of disabledbackground and disabledforground to match the colors of background and forground. If you need this rolled into a class, do it like this:
class MyEntry(Entry):
def __init__(self, *args, **kwds):
Entry.__init__(self, *args, **kwds)
self.config(disabledbackground=self.cget('background'))
self.config(disabledforeground=self.cget('foreground'))
And use it like this:
e = MyEntry(root)
e.config(state=DISABLED) # or state=NORMAL
Note. Be careful when reinventing gui conventions. Having something that looks enabled act disabled can be confusing for users. So don't change this unless you have good reason.
A:
After trawling the ttk documentation, this does the trick:
ttk.Style().map("TEntry",
foreground=[('disabled', 'black')],
fieldbackground=[('disabled','white')]
)
widget['state'] = 'disabled'
| tkinter python: How do remove the input cursor from a ttk.Entry? | I have an instance of ttk.Entry.
The user clicks it.
I have the event bound.
Depending on some condition, I either want the input cursor to appear and allow typing or I essentially want to ignore the click and not have the input cursor appear in the ttk.Entry. I don't want to have to use the readonly or disabled states.
Manipulating focus has not effect.
| [
"Here is a class that does what you ask.\nclass MyEntry(Entry):\n\n def disable(self):\n self.__old_insertontime = self.cget('insertontime')\n self.config(insertontime=0)\n self.bind('<Key>', lambda e: 'break')\n\n def enable(self):\n self.unbind('<Key>')\n if self.cget('ins... | [
1,
0
] | [] | [] | [
"python",
"tkinter",
"ttk"
] | stackoverflow_0004205996_python_tkinter_ttk.txt |
Q:
sage math software: using cli interface, is && operator(i.e. "background and control"?) functionality supported?
I'm new to sage math software. i've been looking though sage documentation to find if the sage cli supports any way to run multiple commands one after another, i.e. behave like bash when using the && operator. for example, on linux:
$ cp file1 file2 && rm file1
at the command line will copy file1 to file2 and after that operation is complete delete file1. for instance i would love to be able to do something like
sage: g = e^-x && g && x = g
from a sage prompt.
Does sage support this? is there a workaround if not?
thanks.
A:
so, the ";" symbol(semicolon) used in place of where i'm used to using && using bash seems to do the trick. if there are any differences i'm not aware of, i'd appreciate the info.
| sage math software: using cli interface, is && operator(i.e. "background and control"?) functionality supported? | I'm new to sage math software. i've been looking though sage documentation to find if the sage cli supports any way to run multiple commands one after another, i.e. behave like bash when using the && operator. for example, on linux:
$ cp file1 file2 && rm file1
at the command line will copy file1 to file2 and after that operation is complete delete file1. for instance i would love to be able to do something like
sage: g = e^-x && g && x = g
from a sage prompt.
Does sage support this? is there a workaround if not?
thanks.
| [
"so, the \";\" symbol(semicolon) used in place of where i'm used to using && using bash seems to do the trick. if there are any differences i'm not aware of, i'd appreciate the info.\n"
] | [
1
] | [] | [] | [
"python",
"sage"
] | stackoverflow_0004209732_python_sage.txt |
Q:
Python - Are class methods multiprocess safe?
I have a class that loops over some data files, processes them, and then writes new data back out. The analysis of each file is completely independent of the others. The class contains information needed by the analysis in its attributes, but the analysis does not need to change any attributes of the class. Thus I can make the analysis of one data file a single method of my class. The analysis could in principle be done in parallel since each data file is independent. As an aside, I was considering making my class iterable.
Can I use the multiprocessing module to spawn processes that are methods of my class? I need to use multiprocessing because I'm using third party code that has a really bad memory leak (fills up all 24Gb of memory after about 100 data files).
If not, how would you go about doing this? Would you just use a normal function called by my class (passing all the information I need as arguments) instead of a method? How are arguments passed to functions in multiprocessing? Does it make a deep copy?
A:
Yes, if you are not updating data on the class itself that needs to be shared across the instances, multiprocessing is the tool for you in this case.
A:
You're not mentioning your process using any external resources, so it should be fork()-safe. Fork duplicates the memory and file descriptors, program state is identical in the parent and the child. Unless you're using windows which can't fork, go for it.
| Python - Are class methods multiprocess safe? | I have a class that loops over some data files, processes them, and then writes new data back out. The analysis of each file is completely independent of the others. The class contains information needed by the analysis in its attributes, but the analysis does not need to change any attributes of the class. Thus I can make the analysis of one data file a single method of my class. The analysis could in principle be done in parallel since each data file is independent. As an aside, I was considering making my class iterable.
Can I use the multiprocessing module to spawn processes that are methods of my class? I need to use multiprocessing because I'm using third party code that has a really bad memory leak (fills up all 24Gb of memory after about 100 data files).
If not, how would you go about doing this? Would you just use a normal function called by my class (passing all the information I need as arguments) instead of a method? How are arguments passed to functions in multiprocessing? Does it make a deep copy?
| [
"Yes, if you are not updating data on the class itself that needs to be shared across the instances, multiprocessing is the tool for you in this case.\n",
"You're not mentioning your process using any external resources, so it should be fork()-safe. Fork duplicates the memory and file descriptors, program state i... | [
1,
0
] | [] | [] | [
"class",
"iterator",
"multiprocessing",
"python"
] | stackoverflow_0004209962_class_iterator_multiprocessing_python.txt |
Q:
Python Interpreter blocks Multithreaded DNS requests?
I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:
from threading import Thread
import socket
class Connection(Thread):
def __init__(self, name, url):
Thread.__init__(self)
self._url = url
self._name = name
def run(self):
print "Connecting...", self._name
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.connect((self._url, 80))
except socket.gaierror:
pass #not interested in it
print "finished", self._name
if __name__ == '__main__':
conns = []
# all invalid addresses to see how they fail / check times
conns.append(Connection("conn1", "www.2eg11erdhrtj.com"))
conns.append(Connection("conn2", "www.e2ger2dh2rtj.com"))
conns.append(Connection("conn3", "www.eg2de3rh1rtj.com"))
conns.append(Connection("conn4", "www.ege2rh4rd1tj.com"))
conns.append(Connection("conn5", "www.ege52drhrtj1.com"))
for conn in conns:
conn.start()
I dont know exactly how long the timeout is, but when running this the following happens:
All Threads start and I get my printouts
Every xx seconds, one thread displays finished, instead of all at once
The Threads finish sequentially, not all at once (timeout = same for all!)
So my only guess is that this has to do with the GIL? Obviously the threads do not perform their task concurrently, only one connection is attempted at a time.
Does anyone know a way around this?
(asyncore doesnt help, and I'd prefer not to use twisted for now)
Isn't it possible to get this simple little thing done with python?
Greetings, Tom
edit:
I am on MacOSX, I just let my friend run this on linux, and he actually does get the results I wished to get. His socket.connects()'s return immediately, even in a non Threaded environment. And even when he sets the sockets to blocking, and timeout to 10 seconds, all his Threads finish at the same time.
Can anyone explain this?
A:
On some systems, getaddrinfo is not thread-safe. Python believes that some such systems are FreeBSD, OpenBSD, NetBSD, OSX, and VMS. On those systems, Python maintains a lock specifically for the netdb (i.e. getaddrinfo and friends).
So if you can't switch operating systems, you'll have to use a different (thread-safe) resolver library, such as twisted's.
A:
if it's suitable you could use the multiprocessing module to enable process-based parallelism
import multiprocessing, socket
NUM_PROCESSES = 5
def get_url(url):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.connect((url, 80))
except socket.gaierror:
pass #not interested in it
return 'finished ' + url
def main(url_list):
pool = multiprocessing.Pool( NUM_PROCESSES )
for output in pool.imap_unordered(get_url, url_list):
print output
if __name__=="__main__":
main("""
www.2eg11erdhrtj.com
www.e2ger2dh2rtj.com
www.eg2de3rh1rtj.com
www.ege2rh4rd1tj.com
www.ege52drhrtj1.com
""".split())
A:
Send DNS requests asynchronously using Twisted Names:
import sys
from twisted.internet import reactor
from twisted.internet import defer
from twisted.names import client
from twisted.python import log
def process_names(names):
log.startLogging(sys.stderr, setStdout=False)
def print_results(results):
for name, (success, result) in zip(names, results):
if success:
print "%s -> %s" % (name, result)
else:
print >>sys.stderr, "error: %s failed. Reason: %s" % (
name, result)
d = defer.DeferredList(map(client.getHostByName, names), consumeErrors=True)
d.addCallback(print_results)
d.addErrback(defer.logError)
d.addBoth(lambda _: reactor.stop())
reactor.callWhenRunning(process_names, """
google.com
www.2eg11erdhrtj.com
www.e2ger2dh2rtj.com
www.eg2de3rh1rtj.com
www.ege2rh4rd1tj.com
www.ege52drhrtj1.com
""".split())
reactor.run()
| Python Interpreter blocks Multithreaded DNS requests? | I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:
from threading import Thread
import socket
class Connection(Thread):
def __init__(self, name, url):
Thread.__init__(self)
self._url = url
self._name = name
def run(self):
print "Connecting...", self._name
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.connect((self._url, 80))
except socket.gaierror:
pass #not interested in it
print "finished", self._name
if __name__ == '__main__':
conns = []
# all invalid addresses to see how they fail / check times
conns.append(Connection("conn1", "www.2eg11erdhrtj.com"))
conns.append(Connection("conn2", "www.e2ger2dh2rtj.com"))
conns.append(Connection("conn3", "www.eg2de3rh1rtj.com"))
conns.append(Connection("conn4", "www.ege2rh4rd1tj.com"))
conns.append(Connection("conn5", "www.ege52drhrtj1.com"))
for conn in conns:
conn.start()
I dont know exactly how long the timeout is, but when running this the following happens:
All Threads start and I get my printouts
Every xx seconds, one thread displays finished, instead of all at once
The Threads finish sequentially, not all at once (timeout = same for all!)
So my only guess is that this has to do with the GIL? Obviously the threads do not perform their task concurrently, only one connection is attempted at a time.
Does anyone know a way around this?
(asyncore doesnt help, and I'd prefer not to use twisted for now)
Isn't it possible to get this simple little thing done with python?
Greetings, Tom
edit:
I am on MacOSX, I just let my friend run this on linux, and he actually does get the results I wished to get. His socket.connects()'s return immediately, even in a non Threaded environment. And even when he sets the sockets to blocking, and timeout to 10 seconds, all his Threads finish at the same time.
Can anyone explain this?
| [
"On some systems, getaddrinfo is not thread-safe. Python believes that some such systems are FreeBSD, OpenBSD, NetBSD, OSX, and VMS. On those systems, Python maintains a lock specifically for the netdb (i.e. getaddrinfo and friends).\nSo if you can't switch operating systems, you'll have to use a different (thread-... | [
15,
2,
2
] | [] | [] | [
"multithreading",
"network_programming",
"python"
] | stackoverflow_0001212716_multithreading_network_programming_python.txt |
Q:
A hashable, flexible identifier in python
I'm trying to make some sort of hashable identifier in python; I need it to identify nodes in a graph. The trouble is that some nodes have different attributes. If the attributes of these nodes are portrayed by dictionaries of the attributes to values:
idA = {'type':'A', 'name':'a_100'}
idB = {'type':'B', 'name':'b_3', 'value':7}
I want __hash__() and __eq__() to use the tuple pairs ((key1,value1), (key2,value2), ...).
Dictionaries would be ideal for this, because I'm going to check these properties fairly frequently, and dictionary lookup should be efficient (I'm using many identifiers and each will have many attributes). But dictionaries are not hashable.
A frozenset of the tuple pairs would hash properly, but would it be efficient for lookup?
If I declare an empty class, and then set attributes for it, that does what I want (possibly using a dictionary under the hood), but I don't know how to hash it. Maybe there's some way to hash it's member values using inspect or dir()?
class identifier():
pass
idA = identifier()
idA.type = 'A'
idA.name = 'a_100'
If there is a way to use a hash (and == operator) based on tuple pairs of (attribute, value), then this would also do what I want.
Or is there some work around that can make the equivalent data type that would satisfy this SAT-type analogy: frozenset is to set as ? is to dict
Thanks for your help.
Edit:
Is this the right direction?
class identifier(dict):
def to_frozenset(self):
return frozenset([(k,self[k]) for k in self])
def __hash__(self):
return hash(self.to_frozenset())
def __eq__(self, rhs):
return self.to_frozenset() == rhs.to_frozenset()
def __ne__(self, rhs):
return not self == rhs
This shifts the computational complexity so that it is fast to lookup an identifier attribute, but slow to hash an identifier or check two identifiers for equality. If there were a way to cache its hash (and disallow its dictionary to change once the hash was cached), and we were guaranteed few hash collisions of identifier types (so checking for equality were rare), then maybe that would be a good solution? Let me know what you think!
A:
There is no frozendict. But a collections.namedtuple is an approximation to that behaviour which may suit you.
A:
Don't inherit from dict, encapsulate it. That way you can make sure it won't be changed.
As for caching, you can remember to_frozenset or its hash. Depending on the use pattern, remember the hash, which allows you to quickly return on hashing and inequality, and compare the frozensets only if the hashes match.
That said, you're much too worried about performance for someone who hasn't coded a benchmark yet. Build the simplest possible implementation. If it's fast you're done. Otherwise, benchmark it, then find an incremental way to improve measured results.
A:
I'm not sure this solves your problem, but if you want an object to be hashable, you can implement it in this fashion:
class Hashable(object):
def __hash__(self):
return hash((self.__class__.__name__,
tuple(self.__dict__.items())))
You'll get the data of the object in structured tuple format, along with the class name as a hash signature of some king. You can even extend dict to use in this class.
| A hashable, flexible identifier in python | I'm trying to make some sort of hashable identifier in python; I need it to identify nodes in a graph. The trouble is that some nodes have different attributes. If the attributes of these nodes are portrayed by dictionaries of the attributes to values:
idA = {'type':'A', 'name':'a_100'}
idB = {'type':'B', 'name':'b_3', 'value':7}
I want __hash__() and __eq__() to use the tuple pairs ((key1,value1), (key2,value2), ...).
Dictionaries would be ideal for this, because I'm going to check these properties fairly frequently, and dictionary lookup should be efficient (I'm using many identifiers and each will have many attributes). But dictionaries are not hashable.
A frozenset of the tuple pairs would hash properly, but would it be efficient for lookup?
If I declare an empty class, and then set attributes for it, that does what I want (possibly using a dictionary under the hood), but I don't know how to hash it. Maybe there's some way to hash it's member values using inspect or dir()?
class identifier():
pass
idA = identifier()
idA.type = 'A'
idA.name = 'a_100'
If there is a way to use a hash (and == operator) based on tuple pairs of (attribute, value), then this would also do what I want.
Or is there some work around that can make the equivalent data type that would satisfy this SAT-type analogy: frozenset is to set as ? is to dict
Thanks for your help.
Edit:
Is this the right direction?
class identifier(dict):
def to_frozenset(self):
return frozenset([(k,self[k]) for k in self])
def __hash__(self):
return hash(self.to_frozenset())
def __eq__(self, rhs):
return self.to_frozenset() == rhs.to_frozenset()
def __ne__(self, rhs):
return not self == rhs
This shifts the computational complexity so that it is fast to lookup an identifier attribute, but slow to hash an identifier or check two identifiers for equality. If there were a way to cache its hash (and disallow its dictionary to change once the hash was cached), and we were guaranteed few hash collisions of identifier types (so checking for equality were rare), then maybe that would be a good solution? Let me know what you think!
| [
"There is no frozendict. But a collections.namedtuple is an approximation to that behaviour which may suit you.\n",
"Don't inherit from dict, encapsulate it. That way you can make sure it won't be changed.\nAs for caching, you can remember to_frozenset or its hash. Depending on the use pattern, remember the hash,... | [
2,
1,
1
] | [] | [] | [
"dictionary",
"hash",
"immutability",
"python"
] | stackoverflow_0004209753_dictionary_hash_immutability_python.txt |
Q:
Python: how to create a hash of nested containers
[Python 3.1]
I am trying to create a hash for a container that may have nested containers in it, with unknown depth. At all levels of the hierarchy, there are only built-in types. What's a good way to do that?
Why I need it:
I am caching the result of some calculations in a pickle object (on disk). I would need to invalidate that cached file if the function is called with different parameters (this happens rarely, so I'm not going to save more than one file to disk). The hash will be used to compare the parameters.
A:
If all the containers are tuples, and all the contained objects are hashable, then the main container should be hashable.
A:
You could just serialize the parameters into something like JSON, and use that for the hash.
A:
I would do it with json serialization as a string [and then hash that string if it's still necessary].
from simplejson import dumps
def hash_data(data):
return hash(dumps(data))
| Python: how to create a hash of nested containers | [Python 3.1]
I am trying to create a hash for a container that may have nested containers in it, with unknown depth. At all levels of the hierarchy, there are only built-in types. What's a good way to do that?
Why I need it:
I am caching the result of some calculations in a pickle object (on disk). I would need to invalidate that cached file if the function is called with different parameters (this happens rarely, so I'm not going to save more than one file to disk). The hash will be used to compare the parameters.
| [
"If all the containers are tuples, and all the contained objects are hashable, then the main container should be hashable.\n",
"You could just serialize the parameters into something like JSON, and use that for the hash.\n",
"I would do it with json serialization as a string [and then hash that string if it's s... | [
2,
1,
0
] | [] | [] | [
"containers",
"hash",
"nested",
"python",
"python_3.x"
] | stackoverflow_0004202017_containers_hash_nested_python_python_3.x.txt |
Q:
Caching online prices fetched via API unless they change
I'm currently working on a site that makes several calls to big name online sellers like eBay and Amazon to fetch prices for certain items. The issue is, currently it takes a few seconds (as far as I can tell, this time is from making the calls) to load the results, which I'd like to be more instant (~10 seconds is too much in my opinion).
I've already cached other information that I need to fetch, but that information is static. Is there a way that I can cache the prices but update them only when needed? The code is in Python and I store info in a mySQL database.
I was thinking of somehow using chron or something along that lines to update it every so often, but it would be nice if there was a simpler and less intense approach to this problem.
Thanks!
A:
You can use memcache to do the caching. The first request will be slow, but the remaining requests should be instant. You'll want a cron job to keep it up to date though. More caching info here: Good examples of python-memcache (memcached) being used in Python?
A:
Have you thought about displaying the cached data, then updating the prices via an ajax callback? You could notify the user if the price changed with a SO type notification bar or similar.
This way the users get results immediately, and updated prices when they are available.
Edit
You can use jquery:
Assume you have a script names getPrices.php that returns a json array of the id of the item, and it's price.
No error handling etc here, just to give you an idea
My necklace: <div id='1'> $123.50 </div><br>
My bracelet: <div id='1'> $13.50 </div><br>
...
<script>
$(document).ready(function() {
$.ajax({ url: "getPrices.php", context: document.body, success: function(data){
for (var price in data)
{
$(price.id).html(price.price);
}
}}));
</script>
A:
You need to handle the following in your application:
get the price
determine if the price has changed
cache the price information
For step 1, you need to consider how often the item prices will change. I would go with your instinct to set a Cron job for a process which will check for new prices on the items (or on sets of items) at set intervals. This is trivial at small scale, but when you have tens of thousands of items the architecture of this system will become very important.
To avoid delays in page load, try to get the information ahead of time as much as possible. I don't know your use case, but it'd be good to prefetch the information as much as possible and avoid having the user wait for an asynchronous JavaScript call to complete.
For step 2, if it's a new item or if the price has changed, update the information in your caching system.
For step 3, you need to determine the best caching system for your needs. As others have suggested, memcached is a possible solution. There are a variety of "NoSQL" databases you could check out, or even cache the results in MySQL.
A:
How are you getting the price? If you are scrapping the data from the normal HTML page using a tool such as BeautifulSoup, that may be slowing down the round-trip time. In this case, it might help to compute a fast checksum (such as MD5) from the page to see if it has changed, before parsing it. If you are using a API which gives a short XML version of the price, this is probably not an issue.
| Caching online prices fetched via API unless they change | I'm currently working on a site that makes several calls to big name online sellers like eBay and Amazon to fetch prices for certain items. The issue is, currently it takes a few seconds (as far as I can tell, this time is from making the calls) to load the results, which I'd like to be more instant (~10 seconds is too much in my opinion).
I've already cached other information that I need to fetch, but that information is static. Is there a way that I can cache the prices but update them only when needed? The code is in Python and I store info in a mySQL database.
I was thinking of somehow using chron or something along that lines to update it every so often, but it would be nice if there was a simpler and less intense approach to this problem.
Thanks!
| [
"You can use memcache to do the caching. The first request will be slow, but the remaining requests should be instant. You'll want a cron job to keep it up to date though. More caching info here: Good examples of python-memcache (memcached) being used in Python?\n",
"Have you thought about displaying the cached d... | [
3,
2,
2,
0
] | [] | [] | [
"caching",
"html",
"mysql",
"python"
] | stackoverflow_0004208989_caching_html_mysql_python.txt |
Q:
Using networkx with my own object
I have my own objects, say pepperoni. I have a list of edges to an from every pepperoni and a list of pepperonis. I then build a graph using networkx. I'm trying to find the weight of the shortest path from one pepperoni to another. However, I'm getting an error as follows, which traces internal things from networkx as follows:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pizza.py", line 437, in shortestPath
cost = nx.shortest_path_length(a, spepp, tpepp, True)
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/generic.py", line 181, in shortest_path_length
paths=nx.dijkstra_path_length(G,source,target)
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/weighted.py", line 119, in dijkstra_path_length
(length,path)=single_source_dijkstra(G,source, weight = weight)
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/weighted.py", line 424, in single_source_dijkstra
edata=iter(G[v].items())
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/classes/graph.py", line 323, in __getitem__
return self.adj[n]
KeyError: <pizza.pepperoni object at 0x100ea2810>
Any idea as to what is the error, or what I have to add to my pizza class in order to not get this KeyError?
Edit: I have my edges formatted correctly. I don't know if the objects can be handled as nodes though.
A:
If you have edges and nodes each as a list, then building a graph in networkx is straightforward. Given that your problem occurs in building your graph object, perhaps the best diagnostic is to go through graph construction in networkx step by step:
import networkx as NX
import string
import random
G = NX.Graph() # initialize the graph
# just generate some synthetic data for the nodes and edges:
my_nodes = [ ch for ch in string.ascii_uppercase ]
my_nodes2 = list(my_nodes)
random.shuffle(my_nodes2)
my_edges = [ t for t in zip(my_nodes, my_nodes2) if not t[0]==t[1] ]
# now add the edges and nodes to the networkx graph object:
G.add_nodes_from(my_nodes)
G.add_edges_from(my_edges)
# look at the graph's properties:
In [87]: len(G.nodes())
Out[87]: 26
In [88]: len(G.edges())
Out[88]: 25
In [89]: G.edges()[:5]
Out[89]: [('A', 'O'), ('A', 'W'), ('C', 'U'), ('C', 'F'), ('B', 'L')]
# likewise, shortest path calculation is straightforward
In [86]: NX.shortest_path(G, source='A', target='D', weighted=False)
Out[86]: ['A', 'W', 'R', 'D']
In my experience, Networkx has an extremely permissive interface, in particular, it will accept a broad range of object types as nodes and edges. A node can be any hashable object except None.
The only thing i can think of that might cause the error you presented in your Q is that perhaps after you crated the graph you directly manipulated the graph object (the dict, *G*), which you shouldn't do--there are plenty of accessor methods.
| Using networkx with my own object | I have my own objects, say pepperoni. I have a list of edges to an from every pepperoni and a list of pepperonis. I then build a graph using networkx. I'm trying to find the weight of the shortest path from one pepperoni to another. However, I'm getting an error as follows, which traces internal things from networkx as follows:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pizza.py", line 437, in shortestPath
cost = nx.shortest_path_length(a, spepp, tpepp, True)
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/generic.py", line 181, in shortest_path_length
paths=nx.dijkstra_path_length(G,source,target)
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/weighted.py", line 119, in dijkstra_path_length
(length,path)=single_source_dijkstra(G,source, weight = weight)
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/algorithms/shortest_paths/weighted.py", line 424, in single_source_dijkstra
edata=iter(G[v].items())
File "/Library/Python/2.6/site-packages/networkx-1.3-py2.6.egg/networkx/classes/graph.py", line 323, in __getitem__
return self.adj[n]
KeyError: <pizza.pepperoni object at 0x100ea2810>
Any idea as to what is the error, or what I have to add to my pizza class in order to not get this KeyError?
Edit: I have my edges formatted correctly. I don't know if the objects can be handled as nodes though.
| [
"If you have edges and nodes each as a list, then building a graph in networkx is straightforward. Given that your problem occurs in building your graph object, perhaps the best diagnostic is to go through graph construction in networkx step by step:\nimport networkx as NX\nimport string\nimport random\n\nG = NX.Gr... | [
3
] | [] | [] | [
"graph_theory",
"networkx",
"python"
] | stackoverflow_0004210616_graph_theory_networkx_python.txt |
Q:
Eliminate this unneeded copy in list.extend
Given two normal python lists, newlist and oldlist, with an integer index < len(oldlist), I'd like to perform the following operation:
newlist.extend(oldlist[index:])
but without creating the intermediate list oldlist[index:], or equivalently,
newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))
without the overhead of a generator. Is that possible without using C?
Edit: This question derived from some looking at the c implementation of some list operations, in particular for list.extend(), when the interpreter determines that it can guess the size of the tail being added to the list, it allocates that full size to the head list and copies the elements as they are generated; for other cases, it allocates a few elements at a time (about eight, if memory serves), and copies elements in a few at a time.
The specific cases when it does the full allocation seemed to be for python lists, and a few other types that have a __len__. As far as I can tell, there's no built in type of 'list view' that would satisfy those requirements.
A:
Don't guess, measure
create = """
oldlist = range(5000)
newlist = range(5000, 10000)
index = 500
"""
tests = [
"newlist.extend(oldlist[index:])",
"newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))",
"newlist.extend(islice(oldlist, index, None))",
"""\
while index < len(oldlist):
newlist.append(oldlist[index])
index+=1""",
]
import timeit
for test in tests:
t = timeit.Timer(create + test, setup='from itertools import islice')
print test, min(t.repeat(number=100000))
newlist.extend(oldlist[index:]) 17.2596559525
newlist.extend(oldlist[i] for i in xrange(index, len(oldlist))) 53.5918159485
newlist.extend(islice(oldlist, index, None)) 19.6523411274
while index < len(oldlist):
newlist.append(oldlist[index])
index+=1 123.556715012
A:
The obvious solution would be:
while index < len(oldlist):
newlist.append(oldlist[index])
index += 1
But be wary of premature optimization, I've never run into a situation in which the loss of readability in this solution would be worth it. And, of course, benchmark all options to make sure that the solution you think is faster, actually is.
A:
appendnew = newlist.append
try:
while 1:
appendnew(oldlist[index])
index += 1
except IndexError:
pass
or, slightly less bogglingly:
appendnew = newlist.append
for i in xrange(index, len(oldlist)):
appendnew(oldlist[i])
A:
Some clues on better benchmarking
Measure the overhead and subtract it off.
Put the code inside a function or method (simulates reality; helps ensure no nasty effects from having variables as global).
from itertools import islice
def f0(newlist, oldlist, index):
pass
def f1(newlist, oldlist, index):
newlist.extend(oldlist[index:])
def f2(newlist, oldlist, index):
newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))
def f3(newlist, oldlist, index):
newlist.extend(islice(oldlist, index, None))
def f4(newlist, oldlist, index):
while index < len(oldlist):
newlist.append(oldlist[index])
index += 1
>python -mtimeit -s"old=range(1000);new=range(5000,10000);ix=500;import xtnd"; "xtnd.f4(new,old,ix)"
If the code being benchmarked has a variable N (in this case N = len(oldlist) - index), benchmark with more than one value of N. If you expect O(N) behaviour, O(1) results should be a cause for investigation.
Also compare results across pairs of candidates with reasonable expectations --- wild variations should be investigated; they could be caused by experimental error.
| Eliminate this unneeded copy in list.extend | Given two normal python lists, newlist and oldlist, with an integer index < len(oldlist), I'd like to perform the following operation:
newlist.extend(oldlist[index:])
but without creating the intermediate list oldlist[index:], or equivalently,
newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))
without the overhead of a generator. Is that possible without using C?
Edit: This question derived from some looking at the c implementation of some list operations, in particular for list.extend(), when the interpreter determines that it can guess the size of the tail being added to the list, it allocates that full size to the head list and copies the elements as they are generated; for other cases, it allocates a few elements at a time (about eight, if memory serves), and copies elements in a few at a time.
The specific cases when it does the full allocation seemed to be for python lists, and a few other types that have a __len__. As far as I can tell, there's no built in type of 'list view' that would satisfy those requirements.
| [
"Don't guess, measure\ncreate = \"\"\"\noldlist = range(5000)\nnewlist = range(5000, 10000)\nindex = 500\n\"\"\"\ntests = [\n \"newlist.extend(oldlist[index:])\",\n \"newlist.extend(oldlist[i] for i in xrange(index, len(oldlist)))\",\n \"newlist.extend(islice(oldlist, index, None))\",\n \"\"\"\\\nwhile ... | [
10,
0,
0,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0004210481_optimization_python.txt |
Q:
A question from code in python's graph theory essays
The code is to determine a path between two nodes for directed graphs. This is the code:
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
Being new to python, I two have small and trivial questions. I hope you don't mind it.
Q1. What does if newpath: in the second last line of the code mean?
Q2. Does this code gives all possible paths in the directed graph?
Thanks.
A:
Q1: This checks whether the call of find_path actually returns something. See the language docs to find out what gets interpreted as true and what as false if the type of the term is not boolean to start with. (In this case, None evaluates to false).
Q2: No: this function gives exactly one path from start to end.
| A question from code in python's graph theory essays | The code is to determine a path between two nodes for directed graphs. This is the code:
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
Being new to python, I two have small and trivial questions. I hope you don't mind it.
Q1. What does if newpath: in the second last line of the code mean?
Q2. Does this code gives all possible paths in the directed graph?
Thanks.
| [
"Q1: This checks whether the call of find_path actually returns something. See the language docs to find out what gets interpreted as true and what as false if the type of the term is not boolean to start with. (In this case, None evaluates to false).\nQ2: No: this function gives exactly one path from start to end.... | [
3
] | [] | [] | [
"delimiter",
"graph_theory",
"if_statement",
"python"
] | stackoverflow_0004210963_delimiter_graph_theory_if_statement_python.txt |
Q:
Reusing django re-usable apps
I was wondering if this would be possible to implement (as an app/middleware):
I install the django-registration app. I then create my site-base app for making some generic page views. I want to put a login form and a registration form on a the front page. So I go in and I modify the /register/login.html and the register/register.html templates to fit my front page design (html stuff). I then go to my main page index.html file and I go to the spot in my html where I want those blocks (login & register) to go, and I add {% load "register/login.html" %} and a {% load "register/register.html" %}. Now, when the urlconf calls my index's view, the template will reach the LOAD trigger and will call the LOGIN view so that all of its form.elements are passed to it, and the REGISTER view is called for its elements too. Then, those completed (rendered) views are passed to my index.html and plugged into the spot where I put the LOAD statements.
Can the above be done currently? My goal is to take the various apps available and plug them into my project without touching any of their code (I want to ensure that I can upgrade the individual apps later and not break anything in my project because I added custom stuff...).
If the above is possible currently, could someone please provide some documentation/tutorials/howtos for best practices in re-using other peoples apps?
A:
There's certainly the {% include %} tag, which allows you to include templates directly inside of another template. It also gets everything that the enclosed template gets, so if you are using the RequestContext that means it has access to everything in the request variable.
However, it seems you're saying that you want to somehow actually call the register view and login views and embed the result into your page. This could in theory be possible by writing a custom tag that calls the URL using an http GET and then outputting the resulting HTML from the request.
I wouldn't recommend this. Instead, for the front page, go ahead and create two forms that point to the appropriate URLs in the django-registration application.
A:
What about simply modifying the views in the app I am re-using to include an extra argument to see if it is being used as a SUBVIEW (and therefore not return render_to_response() ), and check for "FORMNAME" in the request.POST data. Then, if the SUBVIEW (view of app I am re-using) finds its "FORMNAME" in the request.POST it would process the form. If no request.POST data supplied, it would return a dictionary with all the form elements rather than the render_to_response(). I can then call that function in my view for the front page and pass the returned dictionary of values to my template along with any other components. On submit, the function would be called, and if it finds the "Name of form" in the request.POST data (this "Name of form" can be in a hidden field, it will process that form, otherwise it will return the dictionary of form elements, and the next function will be called in my view, which may be related to the django.contrib.django-registration.register() view. This would produce ULTIMATE RE-USABILITY!
This way I also get access to the form.errors!!
My view:
def index(request):
login = django.contrib.register.login(request, ... , Subview=True)
register = django.contrib.register.register(request, ... , Subview=True)
return render_to_response('index.html', {'login_form': login, 'register_form': register})
Alternatively I could fork each app and modify it... which defeats the purpose of re-using the app as an independently maintained package, and rather is treated more like a complex code paste.
| Reusing django re-usable apps | I was wondering if this would be possible to implement (as an app/middleware):
I install the django-registration app. I then create my site-base app for making some generic page views. I want to put a login form and a registration form on a the front page. So I go in and I modify the /register/login.html and the register/register.html templates to fit my front page design (html stuff). I then go to my main page index.html file and I go to the spot in my html where I want those blocks (login & register) to go, and I add {% load "register/login.html" %} and a {% load "register/register.html" %}. Now, when the urlconf calls my index's view, the template will reach the LOAD trigger and will call the LOGIN view so that all of its form.elements are passed to it, and the REGISTER view is called for its elements too. Then, those completed (rendered) views are passed to my index.html and plugged into the spot where I put the LOAD statements.
Can the above be done currently? My goal is to take the various apps available and plug them into my project without touching any of their code (I want to ensure that I can upgrade the individual apps later and not break anything in my project because I added custom stuff...).
If the above is possible currently, could someone please provide some documentation/tutorials/howtos for best practices in re-using other peoples apps?
| [
"There's certainly the {% include %} tag, which allows you to include templates directly inside of another template. It also gets everything that the enclosed template gets, so if you are using the RequestContext that means it has access to everything in the request variable.\nHowever, it seems you're saying that y... | [
0,
0
] | [] | [] | [
"django",
"model_view_controller",
"python",
"web_applications"
] | stackoverflow_0004201948_django_model_view_controller_python_web_applications.txt |
Q:
Python: variable-length tuples
[Python 3.1]
I'm following up on the design concept that tuples should be of known length (see this comment), and unknown length tuples should be replaced with lists in most circumstances. My question is under what circumstances should I deviate from that rule?
For example, I understand that tuples are faster to create from string and numeric literals than lists (see another comment). So, if I have performance-critical code where there are numerous calculations such as sumproduct(tuple1, tuple2), should I redefine them to work on lists despite a performance hit? (sumproduct((x, y, z), (a, b, c)) is defined as x * a + y * b + z * c, and its arguments have unspecified but equal lengths).
And what about the tuple that is automatically built by Python when using def f(*x)? I assume it's not something I should coerce to list every time I use it.
Btw, is (x, y, z) faster to create than [x, y, z] (for variables rather than literals)?
A:
In my mind, the only interesting distinction between tuples and lists is that lists are mutable and tuples are not. The other distinctions that people mention seem completely artificial to me: tuples are like structs and lists are like arrays (this is where the "tuples should be a known length" comes from). But how is struct-ness aligned with immutability? It isn't.
The only distinction that matters is the distinction the language makes: mutability. If you need to modify the object, definitely use a list. If you need to hash the object (as a key in a dict, or an element of a set), then you need it to be immutable, so use a tuple. That's it.
A:
I always use the most the appropriate data structure for the job and do not really worry about if a tuple would save me half a millisecond here or there. Pre-obfuscating your code does not usually pay off in the end. If the code runs too slow you can always profile it later and change the .01% of code where it really matters.
All the things you are talking about are tied in to the implementation of the python version and the hardware it is running on. You can always time those things your self to see what they would be on your machine.
A common example of this is the 'old immutable strings are slow to concatenate' in python. This was true about 10 years ago, and then they changed the implementation in 2.4 or 2.5. If you do your own tests they now run faster than lists, but people are convinced of this still today and use silly constructs that actually ran slower!
A:
under what circumstances should I deviate from that [tuples should be of known length] rule?
None.
It's a matter of meaning. If an object has meaning based on a fixed number of elements, then it's a tuple. (x,y) coordinates, (c,m,y,k) colors, (lat, lon) position, etc., etc.
A tuple has a fixed number of elements based on the problem domain in general and the specifics of the problem at hand.
Designing a tuple with an indefinite number of elements makes little sense. When do we switch from (x,y) to (x,y,z) and then to (x,y,z,w) coordinates? Not by simply concatenating a value as if it's a list? If we're moving from 2-d to 3-d coordinates there's usually some pretty fancy math to map the coordinate systems. Not appending an element to a list.
What does it mean to move from (r,g,b) colors to something else? What is the 4th color in the rgb system? For that matter, what's the fifth color in the cmyk ststem?
Tuples do not change size.
*args is a tuple because it is immutable. Yes, it has an indefinite number of arguments, but it's a rare counter-exmaple to tuples of known, defined sizes.
What to do about an indefinite length tuple. This counter-example is so profound that we have two choices.
Reject the very idea that tuples are fixed-length, and constrained by the problem,. The very idea of (x,y) coordinates and (r,g,b) colors is utterly worthless and wrong because of this counter-example. Fixed-length tuples? Never.
Always convert all *args to lists to always have a fussy level of unthinking conformance to a design principle. Covert to lists? Always.
I love all or nothing choices, since they make software engineering so simplistic and unthinking.
Perhaps, in these corner cases, there's a tiny scrap of "this requires thinking" here. A tiny scrap.
Yes, *args is a tuple. Yes, it's of indefinite length. Yes, it's a counter-example where "fixed by the problem domain" is trumped by "simply immutable".
This leads us to the third choice in the case where a sequence is immutable for a different reason. You'll never mutate it, so it's okay to be a tuple of indefinite size. In the even-more-rare case where you're popping values of *args because you're treating it like a stack or a queue, then you might want to make a list out of it. But we can't pre-solve all possible problems.
Sometimes Thinking Is Required.
When you're doing design, you design a tuple for a reason. To impose a meaningful structure on your data. Fixed-length number of elements? Tuple. Variable number of elements (i.e., mutable)? List.
A:
In this case, you should probably consider using numpy and numpy arrays.
There is some overhead converting to and from numpy arrays, but if you are doing a bunch of calculation it will be much faster
| Python: variable-length tuples | [Python 3.1]
I'm following up on the design concept that tuples should be of known length (see this comment), and unknown length tuples should be replaced with lists in most circumstances. My question is under what circumstances should I deviate from that rule?
For example, I understand that tuples are faster to create from string and numeric literals than lists (see another comment). So, if I have performance-critical code where there are numerous calculations such as sumproduct(tuple1, tuple2), should I redefine them to work on lists despite a performance hit? (sumproduct((x, y, z), (a, b, c)) is defined as x * a + y * b + z * c, and its arguments have unspecified but equal lengths).
And what about the tuple that is automatically built by Python when using def f(*x)? I assume it's not something I should coerce to list every time I use it.
Btw, is (x, y, z) faster to create than [x, y, z] (for variables rather than literals)?
| [
"In my mind, the only interesting distinction between tuples and lists is that lists are mutable and tuples are not. The other distinctions that people mention seem completely artificial to me: tuples are like structs and lists are like arrays (this is where the \"tuples should be a known length\" comes from). Bu... | [
18,
3,
2,
1
] | [] | [] | [
"list",
"performance",
"python",
"python_3.x",
"tuples"
] | stackoverflow_0004210981_list_performance_python_python_3.x_tuples.txt |
Q:
2 django sites on 1 apache virtual host with django login
I have 2 sites, both require login ( I'm using the django provided django.contrib.auth.views.login). When I enter http:// url /siteb , I am redirected to accounts/login and siteb is taken out of the URL creating http:// url /accounts/login. But then I get an error "The requested URL /accounts/login was not found on server"
If I remove the login requirement and go directly to a page I can click around the site without problem (http:// url /siteb/faqa) If I have only one site in apache and use < Location "/" > I don't have a problem logging in and navigating. My issue is when I have 2 sites, both with the login redirect
(Django 1.2.1, Apache 2.2.14, Python 2.6, mod_python just because that's what I was told to use)
< VirtualHost *>
ServerName name
DocumentRoot /etc/sites
< Location "/siteb">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonPath "['/etc/sites', '/etc/sites/siteb'] + sys.path"
PythonOption django.root /siteb
SetEnv DJANGO_SETTINGS_MODULE siteb.settings
PythonInterpreter siteb
PythonDebug on
< /Location>
< Location "/sitea">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonPath "['/etc/sites', '/etc/sites/sitea'] + sys.path"
PythonOption django.root /sitea
SetEnv DJANGO_SETTINGS_MODULE sitea.settings
PythonInterpreter sitea
PythonDebug on
< /Location>
< /VirtualHost>
A:
All of the urls should be prefixed with /sitea/ or /siteb/
Django generally assumes that it is installed at the root of the website.
| 2 django sites on 1 apache virtual host with django login | I have 2 sites, both require login ( I'm using the django provided django.contrib.auth.views.login). When I enter http:// url /siteb , I am redirected to accounts/login and siteb is taken out of the URL creating http:// url /accounts/login. But then I get an error "The requested URL /accounts/login was not found on server"
If I remove the login requirement and go directly to a page I can click around the site without problem (http:// url /siteb/faqa) If I have only one site in apache and use < Location "/" > I don't have a problem logging in and navigating. My issue is when I have 2 sites, both with the login redirect
(Django 1.2.1, Apache 2.2.14, Python 2.6, mod_python just because that's what I was told to use)
< VirtualHost *>
ServerName name
DocumentRoot /etc/sites
< Location "/siteb">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonPath "['/etc/sites', '/etc/sites/siteb'] + sys.path"
PythonOption django.root /siteb
SetEnv DJANGO_SETTINGS_MODULE siteb.settings
PythonInterpreter siteb
PythonDebug on
< /Location>
< Location "/sitea">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonPath "['/etc/sites', '/etc/sites/sitea'] + sys.path"
PythonOption django.root /sitea
SetEnv DJANGO_SETTINGS_MODULE sitea.settings
PythonInterpreter sitea
PythonDebug on
< /Location>
< /VirtualHost>
| [
"All of the urls should be prefixed with /sitea/ or /siteb/\nDjango generally assumes that it is installed at the root of the website.\n"
] | [
0
] | [] | [] | [
"apache2",
"django",
"mod_python",
"python"
] | stackoverflow_0004209773_apache2_django_mod_python_python.txt |
Q:
How to make this Twisted Python Proxy faster?
The code below is an HTTP proxy for content filtering. It uses GET to send the URL of the current site to the server, where it processes it and responds. It runs VERY, VERY, VERY slow. Any ideas on how to make it faster?
Here is the code:
from twisted.internet import reactor
from twisted.web import http
from twisted.web.proxy import Proxy, ProxyRequest
from Tkinter import *
#import win32api
import urllib2
import urllib
import os
import webbrowser
cwd = os.path.abspath(sys.argv[0])[0]
proxies = {}
user = "zachb"
class BlockingProxyRequest(ProxyRequest):
def process(self):
params = {}
params['Location']= self.uri
params['User'] = user
params = urllib.urlencode(params)
req = urllib.urlopen("http://weblock.zbrowntechnology.info/ProgFiles/stats.php?%s" % params, proxies=proxies)
resp = req.read()
req.close()
if resp == "allow":
pass
else:
self.transport.write('''BLOCKED BY ADMIN!''')
self.transport.loseConnection()
ProxyRequest.process(self)
class BlockingProxy(Proxy):
requestFactory = BlockingProxyRequest
factory = http.HTTPFactory()
factory.protocol = BlockingProxy
reactor.listenTCP(8000, factory)
reactor.run()
Anyone have any ideas on how to make this run faster? Or even a better way to write it?
A:
The main cause of slowness in this proxy is probably these three lines:
req = urllib.urlopen("http://weblock.zbrowntechnology.info/ProgFiles/stats.php?%s" % params, proxies=proxies)
resp = req.read()
req.close()
A normal Twisted-based application is single threaded. You have to go out of your way to get threads involved. That means that whenever a request comes in, you are blocking the one and only processing thread on this HTTP request. No further requests are processed until this HTTP request completes.
Try using one of the APIs in twisted.web.client, (eg Agent or getPage). These APIs don't block, so your server will handle concurrent requests concurrently. This should translate into much smaller response times.
| How to make this Twisted Python Proxy faster? | The code below is an HTTP proxy for content filtering. It uses GET to send the URL of the current site to the server, where it processes it and responds. It runs VERY, VERY, VERY slow. Any ideas on how to make it faster?
Here is the code:
from twisted.internet import reactor
from twisted.web import http
from twisted.web.proxy import Proxy, ProxyRequest
from Tkinter import *
#import win32api
import urllib2
import urllib
import os
import webbrowser
cwd = os.path.abspath(sys.argv[0])[0]
proxies = {}
user = "zachb"
class BlockingProxyRequest(ProxyRequest):
def process(self):
params = {}
params['Location']= self.uri
params['User'] = user
params = urllib.urlencode(params)
req = urllib.urlopen("http://weblock.zbrowntechnology.info/ProgFiles/stats.php?%s" % params, proxies=proxies)
resp = req.read()
req.close()
if resp == "allow":
pass
else:
self.transport.write('''BLOCKED BY ADMIN!''')
self.transport.loseConnection()
ProxyRequest.process(self)
class BlockingProxy(Proxy):
requestFactory = BlockingProxyRequest
factory = http.HTTPFactory()
factory.protocol = BlockingProxy
reactor.listenTCP(8000, factory)
reactor.run()
Anyone have any ideas on how to make this run faster? Or even a better way to write it?
| [
"The main cause of slowness in this proxy is probably these three lines:\n req = urllib.urlopen(\"http://weblock.zbrowntechnology.info/ProgFiles/stats.php?%s\" % params, proxies=proxies)\n resp = req.read()\n req.close()\n\nA normal Twisted-based application is single threaded. You have to go out of your ... | [
11
] | [] | [] | [
"http",
"proxy",
"python",
"twisted"
] | stackoverflow_0004211454_http_proxy_python_twisted.txt |
Q:
python list element wise conditional increment
I have been searching this for a while, basically I am trying to conditionally increment a list of element by another list, element-wise...
my code is following, but is there a better way to do it? list comprehension, map??
I think a element-wise operator like ~+= from http://www.python.org/dev/peps/pep-0225/ would be really good, but why is it deferred?
for i in range(1,len(s)):
if s[i]<s[0]:
s[i]+=p[i]
based on some good feedbacks from you guys I have recoded to the following
i=s<s[0]
s[i]+=p[i]
and s,p are both arrays.
p.s still slow than matlab 5 times for one of my code.
A:
Here is a quick version:
# sample data
s = [10, 5, 20]
p = [2,2,2]
# As a one-liner. (You could factor out the lambda)
s = map(lambda (si, pi): si + pi if si < s[0] else si, zip(s,p))
# s is now [10, 7, 20]
This assumes that len(s) <= len(p)
Hope this helps. Let me know. Good luck. :-)
A:
Check this SO question:
Merging/adding lists in Python
Basically, something like:
[sum(a) for a in zip(*[s, p]) if a[0] < 0]
Example:
>>> [sum(a) for a in zip(*[[1, 2, 3], [10, 20, 30]]) if a[0] > 2]
[33]
To clarify, here's what zip does:
>>> zip(*[[1, 2, 3], [4, 5, 6]])
[(1, 4), (2, 5), (3, 6)]
It concatenates two (or more) lists into a list of tuples. You can test for conditions on the elements of each of the tuples.
A:
If you don't want to create a new array, then your options are:
What you proposed (though you might want to use xrange depending on the python version)
Use Numpy arrays for s and p. Then you can do something like s[s<s[0]] += p[s<s[0]] if s and p are the same length.
Use Cython to speed up what you've proposed.
A:
s = [s[i]+p[i]*(s[i]<s[0]) for i in range(1,len(s))]
| python list element wise conditional increment | I have been searching this for a while, basically I am trying to conditionally increment a list of element by another list, element-wise...
my code is following, but is there a better way to do it? list comprehension, map??
I think a element-wise operator like ~+= from http://www.python.org/dev/peps/pep-0225/ would be really good, but why is it deferred?
for i in range(1,len(s)):
if s[i]<s[0]:
s[i]+=p[i]
based on some good feedbacks from you guys I have recoded to the following
i=s<s[0]
s[i]+=p[i]
and s,p are both arrays.
p.s still slow than matlab 5 times for one of my code.
| [
"Here is a quick version:\n# sample data\ns = [10, 5, 20]\np = [2,2,2]\n\n# As a one-liner. (You could factor out the lambda)\ns = map(lambda (si, pi): si + pi if si < s[0] else si, zip(s,p))\n\n# s is now [10, 7, 20]\n\nThis assumes that len(s) <= len(p)\nHope this helps. Let me know. Good luck. :-)\n",
"Check ... | [
2,
1,
1,
0
] | [] | [] | [
"increment",
"list",
"python"
] | stackoverflow_0004210938_increment_list_python.txt |
Q:
Python separating Ajax requests from normal page views
I'm wondering what are some strategies that you've come up when dealing with this. I'm new to the python/django framework and would like to separate the serving of view from the handling of ajax requests (xhr).
I'm thinking of having a separate file xhrHandler.py and route specific POST/GET requests to /xhr/methodname and then delegate the views.py methods to return the view passing along the httprequest for view processing.
Thoughts?
A:
Check request.is_ajax() and delegate wherever you need. Sample handler:
def view_something(request):
if request.is_ajax():
# ajax
else
# not
You can now call different functions (in different files) for the two cases.
If you want to be fancier, use a decorator for the handler that will dispatch ajaxy requests elsewhere:
def reroute_ajaxy(ajax_handler):
def wrap(f):
def decorate(*args, **kwargs):
if args[0].is_ajax():
return ajax_handler(args)
else:
return f(*args, **kwargs)
return decorate
return wrap
def score_ajax_handler(request):
print "score ajax handler"
@reroute_ajaxy(score_ajax_handler)
def score_handler(request):
print "score handler"
And some mock testing to exercise it:
class ReqMock:
def __init__(self, ajax=False):
self.ajax = ajax
def is_ajax(self):
return self.ajax
score_handler(ReqMock(True))
score_handler(ReqMock(False))
Produces:
score ajax handler
score handler
| Python separating Ajax requests from normal page views | I'm wondering what are some strategies that you've come up when dealing with this. I'm new to the python/django framework and would like to separate the serving of view from the handling of ajax requests (xhr).
I'm thinking of having a separate file xhrHandler.py and route specific POST/GET requests to /xhr/methodname and then delegate the views.py methods to return the view passing along the httprequest for view processing.
Thoughts?
| [
"Check request.is_ajax() and delegate wherever you need. Sample handler:\ndef view_something(request):\n if request.is_ajax():\n # ajax\n else\n # not\n\nYou can now call different functions (in different files) for the two cases.\nIf you want to be fancier, use a decorator for the handler that wi... | [
3
] | [] | [] | [
"ajax",
"design_patterns",
"django",
"python",
"xmlhttprequest"
] | stackoverflow_0004211883_ajax_design_patterns_django_python_xmlhttprequest.txt |
Q:
How to speed up this Python code?
I've got the following tiny Python method that is by far the performance hotspot (according to my profiler, >95% of execution time is spent here) in a much larger program:
def topScore(self, seq):
ret = -1e9999
logProbs = self.logProbs # save indirection
l = len(logProbs)
for i in xrange(len(seq) - l + 1):
score = 0.0
for j in xrange(l):
score += logProbs[j][seq[j + i]]
ret = max(ret, score)
return ret
The code is being run in the Jython implementation of Python, not CPython, if that matters. seq is a DNA sequence string, on the order of 1,000 elements. logProbs is a list of dictionaries, one for each position. The goal is to find the maximum score of any length l (on the order of 10-20 elements) subsequence of seq.
I realize all this looping is inefficient due to interpretation overhead and would be a heck of a lot faster in a statically compiled/JIT'd language. However, I'm not willing to switch languages. First, I need a JVM language for the libraries I'm using, and this kind of constrains my choices. Secondly, I don't want to translate this code wholesale into a lower-level JVM language. However, I'm willing to rewrite this hotspot in something else if necessary, though I have no clue how to interface it or what the overhead would be.
In addition to the single-threaded slowness of this method, I also can't get the program to scale much past 4 CPUs in terms of parallelization. Given that it spends almost all its time in the 10-line hotspot I've posted, I can't figure out what the bottleneck could be here.
A:
The reason it is slow is because it is O(N*N)
The maximum subsequence algorithm may help you improve this
A:
if topScore is called repeatedly for same seq you could memoize its value.
E.g. http://code.activestate.com/recipes/52201/
A:
i don't have any idea what i'm doing but maybe this can help speed up your algo:
ret = -1e9999
logProbs = self.logProbs # save indirection
l = len(logProbs)
scores = collections.defaultdict(int)
for j in xrange(l):
prob = logProbs[j]
for i in xrange(len(seq) - l + 1):
scores[i] += prob[seq[j + i]]
ret = max(ret, max(scores.values()))
A:
What about precomputing xrange(l) outside the for i loop?
A:
Nothing jumps out as being slow. I might rewrite the inner loop like this:
score = sum(logProbs[j][seq[j+i]] for j in xrange(l))
or even:
seqmatch = zip(seq[i:i+l], logProbs)
score = sum(posscores[base] for base, posscores in seqmatch)
but I don't know that either would save much time.
It might be marginally quicker to store DNA bases as integers 0-3, and look up the scores from a tuple instead of a dictionary. There'll be a performance hit on translating letters to numbers, but that only has to be done once.
A:
Definitely use numpy and store logProbs as a 2D array instead of a list of dictionaries. Also store seq as a 1D array of (short) integers as suggested above. This will help if you don't have to do these conversions every time you call the function (doing these conversions inside the function won't save you much). You can them eliminate the second loop:
import numpy as np
...
print np.shape(self.logProbs) # (20, 4)
print np.shape(seq) # (1000,)
...
def topScore(self, seq):
ret = -1e9999
logProbs = self.logProbs # save indirection
l = len(logProbs)
for i in xrange(len(seq) - l + 1):
score = np.sum(logProbs[:,seq[i:i+l]])
ret = max(ret, score)
return ret
What you do after that depends on which of these 2 data elements changes the most often:
If logProbs generally stays the same and you want to run many DNA sequences through it, then consider stacking your DNA sequences as a 2D array. numpy can loop through the 2D array very quickly so if you have 200 DNA sequences to process, it will only take a little longer than a single.
Finally, if you really need speed up, use scipy.weave. This is a very easy way to write a few lines of fast C to accelerate you loops. However, I recommend scipy >0.8.
A:
You can try hoisting more than just self.logProbs outside the loops:
def topScore(self, seq):
ret = -1e9999
logProbs = self.logProbs # save indirection
l = len(logProbs)
lrange = range(l)
for i in xrange(len(seq) - l + 1):
score = 0.0
for j in lrange:
score += logProbs[j][seq[j + i]]
if score > ret: ret = score # avoid lookup and function call
return ret
A:
I doubt it will make a significant difference, but you could try changing:
for j in xrange(l):
score += logProbs[j][seq[j + i]]
to
for j,lP in enumerate(logProbs):
score += lP[seq[j + i]]
or even hoisting that enumeration outside the seq loop.
| How to speed up this Python code? | I've got the following tiny Python method that is by far the performance hotspot (according to my profiler, >95% of execution time is spent here) in a much larger program:
def topScore(self, seq):
ret = -1e9999
logProbs = self.logProbs # save indirection
l = len(logProbs)
for i in xrange(len(seq) - l + 1):
score = 0.0
for j in xrange(l):
score += logProbs[j][seq[j + i]]
ret = max(ret, score)
return ret
The code is being run in the Jython implementation of Python, not CPython, if that matters. seq is a DNA sequence string, on the order of 1,000 elements. logProbs is a list of dictionaries, one for each position. The goal is to find the maximum score of any length l (on the order of 10-20 elements) subsequence of seq.
I realize all this looping is inefficient due to interpretation overhead and would be a heck of a lot faster in a statically compiled/JIT'd language. However, I'm not willing to switch languages. First, I need a JVM language for the libraries I'm using, and this kind of constrains my choices. Secondly, I don't want to translate this code wholesale into a lower-level JVM language. However, I'm willing to rewrite this hotspot in something else if necessary, though I have no clue how to interface it or what the overhead would be.
In addition to the single-threaded slowness of this method, I also can't get the program to scale much past 4 CPUs in terms of parallelization. Given that it spends almost all its time in the 10-line hotspot I've posted, I can't figure out what the bottleneck could be here.
| [
"The reason it is slow is because it is O(N*N)\nThe maximum subsequence algorithm may help you improve this\n",
"if topScore is called repeatedly for same seq you could memoize its value. \nE.g. http://code.activestate.com/recipes/52201/\n",
"i don't have any idea what i'm doing but maybe this can help speed up... | [
2,
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"java",
"jvm",
"jython",
"performance",
"python"
] | stackoverflow_0004209781_java_jvm_jython_performance_python.txt |
Q:
Performance_Python get union of 2 lists of tuple according to 2 out of the 3 elements of the tuple
My program is not doing a great job. In a loop, data from each processor (list of tuple) are gathered into the master processor that needs to clean it by removing similar element.
I found a lot of interesting clue on internet and especially in this site about union of list. However, i have not managed to apply it to my problem.
My aim is to get rid of tuple whose its two last element are similar to another tuple in the list . for example:
list1=[[a,b,c],[d,e,f],[g,h,i]]
list2=[[b,b,c],[d,e,a],[k,h,i]]
the result should be:
final=[[a,b,c],[d,e,f],[g,h,i],[d,e,a]]
Right now I'm using loops and break but I'm hoping to make this process faster.
here is what my code looks like (result and temp are the lists I want to get union from)
on python2.6.
for k in xrange(len(temp)):
u=0
#index= next((j for j in xrange(lenres) if temp[k][1:3] == result[j][1:3]),None)
for j in xrange(len(result)):
if temp[k][1:3] == result[j][1:3]:
u=1
break
if u==0:
#if index is None:
result.append([temp[k][0],temp[k][1],temp[k][2]])
Thanks for your help
Herve
A:
Below is our uniques function. It takes arguments l (list) and f (function), returns list with duplicates removed (in the same order). Duplicates are defined by: b is duplicate of a iff f(b) == f(a).
def uniques(l, f = lambda x: x):
return [x for i, x in enumerate(l) if f(x) not in [f(y) for y in l[:i]]]
We define lastTwo as follows:
lastTwo = lambda x: x[-2:]
For your problem we use it as follows:
>>> list1
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> list2
[('b', 'b', 'c'), ('d', 'e', 'a'), ('k', 'h', 'i')]
>>> uniques(list1+list2, lastTwo)
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('d', 'e', 'a')]
If the usecase you describe comes up a lot you may want to define
def hervesMerge(l1, l2):
return uniques(l1+l2, lambda x: x[-2:])
Identity is our default f but it can be anything (so long as it is defined for all elements of the list, since they can be of any type).
f can be sum of a list, odd elements of a list, prime factors of an integer, anything. (Just remember that if its injective theres no point! Add by constant, linear functions, etc will work no differently than identity bc its f(x) == f(y) w/ x != y that makes the difference)
>>> list1
[(1, 2, 3, 4), (2, 5), (6, 2, 2), (3, 4), (8, 3), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)]
>>> uniques(list1, sum)
[(1, 2, 3, 4), (2, 5), (8, 3)]
>>> uniques(list1, lambda x: reduce(operator.mul, x)) #product
[(1, 2, 3, 4), (2, 5), (3, 4), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)]
>>> uniques([1,2,3,4,1,2]) #defaults to identity
[1, 2, 3, 4]
You seemed concerned about speed, but my answer really focused on shortness/flexibility without significant (or any?) speed improvment. For bigger lists where speed is z concern, you want to take advantage of hashable checks and the fact that list1 and list2 are known to have no duplicates
>>> s = frozenset(i[-2:] for i in list1)
>>> ans = list(list1) #copy list1
>>> for i in list2:
if i[-2:] not in s: ans.append(i)
>>> ans
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('d', 'e', 'a')]
OR allowing disordering
>>> d = dict()
>>> for i in list2 + list1:
d[i[-2:]] = i
>>> d.values()
[('d', 'e', 'f'), ('a', 'b', 'c'), ('g', 'h', 'i'), ('d', 'e', 'a')]
--Edit--
You should always be able to avoid un-pythonic looping like you post in your question. Here is your exact code with the loops changed:
for k in temp:
u=0
for j in result:
if k[1:3] == j[1:3]:
u=1
break
if u==0:
#if index is None:
result.append([k[0],k[1],k[2]]) // k
result and temp are iterable, and for anything iterable you can put it directly in the for loop without eanges. If for some reason you explicitly need the index (this is not such a case, but I have one above) you can use enumerate.
A:
Here's a simple solution using a set:
list1=[('a','b','c'),('d','e','f'),('g','h','i')]
list2=[('b','b','c'),('d','e','a'),('k','h','i')]
set1 = set([A[1:3] for A in list1])
final = list1 + [A for A in list2 if A[1:3] not in set1]
However, if your list1 and list2 aren't actually made of tuples, then you will have to put tuple() around A[1:3].
| Performance_Python get union of 2 lists of tuple according to 2 out of the 3 elements of the tuple | My program is not doing a great job. In a loop, data from each processor (list of tuple) are gathered into the master processor that needs to clean it by removing similar element.
I found a lot of interesting clue on internet and especially in this site about union of list. However, i have not managed to apply it to my problem.
My aim is to get rid of tuple whose its two last element are similar to another tuple in the list . for example:
list1=[[a,b,c],[d,e,f],[g,h,i]]
list2=[[b,b,c],[d,e,a],[k,h,i]]
the result should be:
final=[[a,b,c],[d,e,f],[g,h,i],[d,e,a]]
Right now I'm using loops and break but I'm hoping to make this process faster.
here is what my code looks like (result and temp are the lists I want to get union from)
on python2.6.
for k in xrange(len(temp)):
u=0
#index= next((j for j in xrange(lenres) if temp[k][1:3] == result[j][1:3]),None)
for j in xrange(len(result)):
if temp[k][1:3] == result[j][1:3]:
u=1
break
if u==0:
#if index is None:
result.append([temp[k][0],temp[k][1],temp[k][2]])
Thanks for your help
Herve
| [
"Below is our uniques function. It takes arguments l (list) and f (function), returns list with duplicates removed (in the same order). Duplicates are defined by: b is duplicate of a iff f(b) == f(a). \ndef uniques(l, f = lambda x: x):\n return [x for i, x in enumerate(l) if f(x) not in [f(y) for y in l[:i]]]... | [
1,
1
] | [] | [] | [
"list",
"python",
"tuples",
"union"
] | stackoverflow_0004211175_list_python_tuples_union.txt |
Q:
Python pickling error when using sessions
In my django app I was creating an extended user profile using session vars. But when registration form was saved and user was about to create, I got following error :
Traceback (most recent call last):
File "\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "\Python26\Lib\site-packages\django\core\handlers\wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "\Python26\Lib\site-packages\django\contrib\sessions\middleware.py", line 36, in process_response
request.session.save()
File "\Python26\Lib\site-packages\django\contrib\sessions\backends\db.py", line 53, in save
session_data = self.encode(self._get_session(no_load=must_create)),
File "\Python26\Lib\site-packages\django\contrib\sessions\backends\base.py", line 88, in encode
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
PicklingError: Can't pickle <type 'cStringIO.StringO'>: attribute lookup cStringIO.StringO failed
I've googled for an answer, but found nothing interesting. Any workarounds for this ?
A:
It appears you have a cStringIO object in your session (perhaps an uploaded file?), these cannot be pickled. Either write custom pickling code or make sure all your session data can be serialized.
A:
Something weird going on here, because the error refers to cStringIO.StringO whereas the class is actually cStringIO.StringIO, with an extra I. Have you misspelled the name somewhere?
A:
In support of Ivo's answer, here's a reference I found which may explain this: http://bugs.python.org/issue5345
This is not a typo. cStringIO.StringIO
is a factory function that returns
either a cStringO object (for writing)
or cStringI (for reading). If this
behavior causes a problem to you, then
consider using StringIO.StringIO.
Alternatively, you could upgrade to
Python 2.7 or 3.0 and use
io.StringIO() which doesn't have this
limitation.
| Python pickling error when using sessions | In my django app I was creating an extended user profile using session vars. But when registration form was saved and user was about to create, I got following error :
Traceback (most recent call last):
File "\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "\Python26\Lib\site-packages\django\core\handlers\wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "\Python26\Lib\site-packages\django\contrib\sessions\middleware.py", line 36, in process_response
request.session.save()
File "\Python26\Lib\site-packages\django\contrib\sessions\backends\db.py", line 53, in save
session_data = self.encode(self._get_session(no_load=must_create)),
File "\Python26\Lib\site-packages\django\contrib\sessions\backends\base.py", line 88, in encode
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
PicklingError: Can't pickle <type 'cStringIO.StringO'>: attribute lookup cStringIO.StringO failed
I've googled for an answer, but found nothing interesting. Any workarounds for this ?
| [
"It appears you have a cStringIO object in your session (perhaps an uploaded file?), these cannot be pickled. Either write custom pickling code or make sure all your session data can be serialized.\n",
"Something weird going on here, because the error refers to cStringIO.StringO whereas the class is actually cStr... | [
4,
1,
1
] | [] | [] | [
"django",
"pickle",
"python",
"session_variables"
] | stackoverflow_0003642107_django_pickle_python_session_variables.txt |
Q:
ImportError: cannot import name tz (psycopg2)
I am using Windows XP, and using Python run time from http://www.python.org/ftp/python/2.7/python-2.7.msi
If I am running in standalone application, import psycopg2 doesn't cause me any trouble. However, when come to mod_wsgi + apache, I will get the following error
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] mod_wsgi (pid=2832): Target WSGI script 'C:/Projects/SandBox/web/script/index.py' cannot be loaded as Python module.
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] mod_wsgi (pid=2832): Exception occurred processing WSGI script 'C:/Projects/SandBox/web/script/index.py'.
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] Traceback (most recent call last):
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] File "C:/Projects/SandBox/web/script/index.py", line 9, in <module>
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] import psycopg2
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] File "build\\bdist.win32\\egg\\psycopg2\\__init__.py", line 65, in <module>
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] from psycopg2 import tz
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] ImportError: cannot import name tz
Here is the python script.
import sys, os
sys.path.append(os.path.dirname(__file__))
import psycopg2
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
and here is the httpd.conf file.
LoadModule wsgi_module modules/mod_wsgi-win32-ap22py27-3.3.so
WSGIScriptAlias / "C:/Projects/SandBox/web/"
<Directory "C:/Projects/SandBox/web">
AllowOverride None
Options None
Order deny,allow
Allow from all
</Directory>
I check the archive C:\Python27\Lib\site-packages\psycopg2-2.2.2-py2.7-win32.egg\, there is C:\Python27\Lib\site-packages\psycopg2-2.2.2-py2.7-win32.egg\psycopg2\tz.py
A:
My guess would be that Python doesn't know your egg cache location (or doesn't have privileges to it). You just need to set that. More information here. Try setting the WSGIPythonEggs directive.
| ImportError: cannot import name tz (psycopg2) | I am using Windows XP, and using Python run time from http://www.python.org/ftp/python/2.7/python-2.7.msi
If I am running in standalone application, import psycopg2 doesn't cause me any trouble. However, when come to mod_wsgi + apache, I will get the following error
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] mod_wsgi (pid=2832): Target WSGI script 'C:/Projects/SandBox/web/script/index.py' cannot be loaded as Python module.
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] mod_wsgi (pid=2832): Exception occurred processing WSGI script 'C:/Projects/SandBox/web/script/index.py'.
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] Traceback (most recent call last):
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] File "C:/Projects/SandBox/web/script/index.py", line 9, in <module>
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] import psycopg2
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] File "build\\bdist.win32\\egg\\psycopg2\\__init__.py", line 65, in <module>
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] from psycopg2 import tz
[Thu Nov 18 14:26:51 2010] [error] [client 127.0.0.1] ImportError: cannot import name tz
Here is the python script.
import sys, os
sys.path.append(os.path.dirname(__file__))
import psycopg2
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
and here is the httpd.conf file.
LoadModule wsgi_module modules/mod_wsgi-win32-ap22py27-3.3.so
WSGIScriptAlias / "C:/Projects/SandBox/web/"
<Directory "C:/Projects/SandBox/web">
AllowOverride None
Options None
Order deny,allow
Allow from all
</Directory>
I check the archive C:\Python27\Lib\site-packages\psycopg2-2.2.2-py2.7-win32.egg\, there is C:\Python27\Lib\site-packages\psycopg2-2.2.2-py2.7-win32.egg\psycopg2\tz.py
| [
"My guess would be that Python doesn't know your egg cache location (or doesn't have privileges to it). You just need to set that. More information here. Try setting the WSGIPythonEggs directive.\n"
] | [
1
] | [] | [] | [
"apache",
"mod_wsgi",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0004212240_apache_mod_wsgi_postgresql_psycopg2_python.txt |
Q:
How to submit form on webpage in PYTHON?
I want to tick checkboxes, select radio buttons, write in text boxes and finally click on submit button to submit the form on a page. Programming in PYTHON only. How do i achieve this?
A:
There are quite some solution. You can explore them and come back with a program, if it does not work.
Mechanize: http://wwwsearch.sourceforge.net/mechanize/
Python Auto Fill with Mechanize
Twill : - http://twill.idyll.org/
Python Paste: http://pythonpaste.org/
PAMIE: http://pamie.sourceforge.net/
| How to submit form on webpage in PYTHON? | I want to tick checkboxes, select radio buttons, write in text boxes and finally click on submit button to submit the form on a page. Programming in PYTHON only. How do i achieve this?
| [
"There are quite some solution. You can explore them and come back with a program, if it does not work.\n\nMechanize: http://wwwsearch.sourceforge.net/mechanize/\n\nPython Auto Fill with Mechanize\n\nTwill : - http://twill.idyll.org/\nPython Paste: http://pythonpaste.org/\nPAMIE: http://pamie.sourceforge.net/\n\n"
... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004212759_python.txt |
Q:
ValueError in Django when trying to edit and .save() IP addresses
Error received:
Exception Type: ValueError at /institutes_admin/
Exception Value: invalid literal for int() with base 10: ''
Full traceback at: http://www.pastie.org/1307821
A:
I would say that you updated an instance variable on your model which should be an integer but cannot be type cast to an integer correctly.
| ValueError in Django when trying to edit and .save() IP addresses | Error received:
Exception Type: ValueError at /institutes_admin/
Exception Value: invalid literal for int() with base 10: ''
Full traceback at: http://www.pastie.org/1307821
| [
"I would say that you updated an instance variable on your model which should be an integer but cannot be type cast to an integer correctly.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004212786_django_python.txt |
Q:
In which "real-use" cases item.__dict__.iteritems() is used?
Yesterday i was reading some questions here on SO and i came to know item.__dict__.iteritems().
I must admit that i do not know how, when or why use that, and i also admit it looks beautiful, pythonic.
So, what are some "real-world" uses of that?
A:
Honestly, it has almost no real life use cases aside from introspection. In most cases, inspect.getmembers will be better (though it's not a generator: if your classes have enough attributes for that to really be a problem than it's the least of them)
The difference is that inspect.gemembers will get both class and instance attributes (and do so all the way up the inheritance chain) whereas only instance attributes live in instance.__dict__.
>>> class A(object):
... a = 'a'
...
>>> a = A()
>>> a.a
'a'
>>> a.__dict__
{}
>>> a.b = 'b'
>>> a.__dict__
{'b': 'b'}
>>> import inspect
>>> inspect.getmembers(a)
[('__class__', <class '__main__.A'>),
('__delattr__', <method-wrapper '__delattr__' of A object at 0xb774da8c>),
('__dict__', {'b': 'b'}), ('__doc__', None),
('__format__', <built-in method __format__ of A object at 0xb774da8c>),
# Snipped for brevity
# ....
('__subclasshook__', <built-in method __subclasshook__ of type object at 0x87b172c>),
('__weakref__', None), ('a', 'a'), ('b', 'b')]
>>> list(a.__dict__.iteritems())
[('b', 'b')]
In general, iteritems is fairly useful anytime you want to look at the key, value entries in a dictionary without expanding them into a list of tuples all at once. It happens to not be incredibly useful when called on this particular dictionary.
| In which "real-use" cases item.__dict__.iteritems() is used? | Yesterday i was reading some questions here on SO and i came to know item.__dict__.iteritems().
I must admit that i do not know how, when or why use that, and i also admit it looks beautiful, pythonic.
So, what are some "real-world" uses of that?
| [
"Honestly, it has almost no real life use cases aside from introspection. In most cases, inspect.getmembers will be better (though it's not a generator: if your classes have enough attributes for that to really be a problem than it's the least of them)\nThe difference is that inspect.gemembers will get both class a... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004213188_python.txt |
Q:
Detect if python script is run from console or by crontab
Imagine a script is running in these 2 sets of "conditions":
live action, set up in sudo crontab
debug, when I run it from console ./my-script.py
What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.
Is there a convention about how to do this? Is there a variable that can tell me who the script owner is? Whether script has a console at stdout? Run a ps | grep to determine that?
Thank you for your time.
A:
Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:
import sys, os
if os.isatty(sys.stdin.fileno()):
# Debug mode.
pass
else:
# Cron mode.
pass
A:
You could add an environment variable to the crontab line and check, inside your python application, if the environment variable is set.
crontab's configuration file:
CRONTAB=true
# run five minutes after midnight, every day
5 0 * * * /path/to/your/pythonscript
Python code:
import os
if os.getenv('CRONTAB') == 'true':
# do your crontab things
else:
# do your debug things
A:
Use a command line option that only cron will use.
Or a symlink to give the script a different name when called by cron. You can then use sys.argv[0]to distinguish between the two ways to call the script.
| Detect if python script is run from console or by crontab | Imagine a script is running in these 2 sets of "conditions":
live action, set up in sudo crontab
debug, when I run it from console ./my-script.py
What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.
Is there a convention about how to do this? Is there a variable that can tell me who the script owner is? Whether script has a console at stdout? Run a ps | grep to determine that?
Thank you for your time.
| [
"Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:\nimport sys, os\nif os.isatty(sys.stdin.fileno()):\n # Debug mode.\n pass\nelse:\n # Cron mode.\n pass\n\n",
"You could add an environment variable to the crontab line and check, inside your python application, if the ... | [
37,
9,
4
] | [] | [] | [
"bash",
"crontab",
"environment_variables",
"python"
] | stackoverflow_0004213091_bash_crontab_environment_variables_python.txt |
Q:
Installing MySQLdb windows for Python 2.5
I have seen this issue come up a lot on these discussion boards but I am still having trouble finding an answer. I am trying to install MySQLdb for Python 2.5 on my Windows Vista machine. I grabbed the installation file from this link
http://sourceforge.net/projects/mysql-python/reviews/
I then opened my Windows command prompt and entered "cd MYSQL-python-1.2.3".
I then entered "python setup.py build"
At this point, it gives me an error: "File setup.py, line 5, in module ImportError: No module named setuptools"
Can anyone give me some guidance on what I should do next? I have searched the web for days regarding this issue.....I have seen several posts saying that there is no good solution for this when running Python 2.5 on Windows. I hope this isn't the case. Thanks!
-Pete
A:
You can install first the setuptools for python 2.5, you can find it here http://pypi.python.org/pypi/setuptools
search for where it says:setuptools-0.6c11.win32-py2.3.exe (md5)
After you install this, then try again installing mysqldb
| Installing MySQLdb windows for Python 2.5 | I have seen this issue come up a lot on these discussion boards but I am still having trouble finding an answer. I am trying to install MySQLdb for Python 2.5 on my Windows Vista machine. I grabbed the installation file from this link
http://sourceforge.net/projects/mysql-python/reviews/
I then opened my Windows command prompt and entered "cd MYSQL-python-1.2.3".
I then entered "python setup.py build"
At this point, it gives me an error: "File setup.py, line 5, in module ImportError: No module named setuptools"
Can anyone give me some guidance on what I should do next? I have searched the web for days regarding this issue.....I have seen several posts saying that there is no good solution for this when running Python 2.5 on Windows. I hope this isn't the case. Thanks!
-Pete
| [
"You can install first the setuptools for python 2.5, you can find it here http://pypi.python.org/pypi/setuptools\nsearch for where it says:setuptools-0.6c11.win32-py2.3.exe (md5)\nAfter you install this, then try again installing mysqldb\n"
] | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004211062_mysql_python.txt |
Q:
termination of a twistd application in python
I am trying to write an application with twistd library written for Python. The application file ends like the following:
factory = protocol.ServerFactory()
factory.protocol = EchoServer
application = service.Application("Echo")
internet.TCPServer(8001, factory).setServiceParent(application)
I want to run something before my appication terminates (e.g. close a file). Does anyone know how to do that? because this is an event-handler and I don't know where the clean-up function is called.
A:
You need to add code to the startService and stopService methods of the Service.
One way would be something like this:
from twisted.application import service
from twisted.internet import protocol
class MyService(service.Service):
def __init__(self,port=8001):
self.port = port
def startService(self):
self.factory = protocol.ServerFactory()
self.factory.protocol = EchoServer
from twisted.internet import reactor
reactor.callWhenRunning(self.startListening)
def startListening(self):
from twisted.internet import reactor
self.listener = reactor.listenTCP(self.port,self.factory)
print "Started listening"
def stopService(self):
self.listener.stopListening()
# Any other tidying
application = service.Application("Echo")
MyService().setServiceParent(application)
| termination of a twistd application in python | I am trying to write an application with twistd library written for Python. The application file ends like the following:
factory = protocol.ServerFactory()
factory.protocol = EchoServer
application = service.Application("Echo")
internet.TCPServer(8001, factory).setServiceParent(application)
I want to run something before my appication terminates (e.g. close a file). Does anyone know how to do that? because this is an event-handler and I don't know where the clean-up function is called.
| [
"You need to add code to the startService and stopService methods of the Service.\nOne way would be something like this:\nfrom twisted.application import service\nfrom twisted.internet import protocol\n\nclass MyService(service.Service):\n def __init__(self,port=8001):\n self.port = port\n def startService(sel... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004211932_python.txt |
Q:
Python function parameter: tuple/list
My function expects a list or a tuple as a parameter. It doesn't really care which it is, all it does is pass it to another function that accepts either a list or tuple:
def func(arg): # arg is tuple or list
another_func(x)
# do other stuff here
Now I need to modify the function slightly, to process an additional element:
def func(arg): #arg is tuple or list
another_func(x + ['a'])
# etc
Unfortunately this is not going to work: if arg is tuple, I must say x + ('a',).
Obviously, I can make it work by coercing arg to list. But it isn't neat.
Is there a better way of doing that? I can't force callers to always pass a tuple, of course, since it simply shifts to work to them.
A:
If another_func just wants a iterable you can pass itertools.chain(x,'a') to it.
A:
What about changing the other function to accept a list of params instead ?
def func(arg): # arg is tuple or list
another_func('a', *x)
A:
how about:
l = ['a']
l.extend(x)
Edit:
Re-reading question, I think this is more what you want (the use of arg and x was a little confusing):
tuple(arg) + ('a',)
As others have said, this is probably not the most efficient way, but it is very clear. If your tuples/lists are small, I might use this over less clear solutions as the performance hit will be negligible. If your lists are large, use the more efficient solutions.
A:
def f(*args):
print args
def a(*args):
k = list(args)
k.append('a')
f(*k)
a(1, 2, 3)
Output:
(1, 2, 3, 'a')
A:
If an iterable is enough you can use itertools.chain, but be aware that if function A (the first one called), also iterates over the iterable after calling B, then you might have problems since iterables cannot be rewinded. In this case you should opt for a sequence or use iterable.tee to make a copy of the iterable:
import itertools as it
def A(iterable):
iterable, backup = it.tee(iterable)
res = B(it.chain(iterable, 'a'))
#do something with res
for elem in backup:
#do something with elem
def B(iterable):
for elem in iterable:
#do something with elem
Even though itertools.tee isn't really that efficient if B consumes all or most of the iterable, at that point it's simpler to just convert iterable to a tuple or a list.
A:
My suggestion:
def foo(t):
bar(list(t) + [other])
This is not very efficient though, you'd be better off passing around mutable things if you're going to be, well, mutating them.
A:
You can use the type of the iterable passed to the first function to construct what you pass to the second:
from itertools import chain
def func(iterable):
it = iter(iterable)
another_func(type(iterable)(chain(it, ('a',))))
def another_func(arg):
print arg
func((1,2))
# (1, 2, 'a')
func([1,2])
# [1, 2, 'a']
A:
Have your function accept any iterable. Then use itertools.chain to add whatever sequence you want to the iterable.
from itertools import chain
def func(iterable):
another_func(chain(iterable, ('a',)))
A:
I'd say Santiago Lezica's answer of doing
def foo(t):
bar(list(t) + [other])
is the best because it is the simplest. (no need to import itertools stuff and use much less readable chain calls). But only use it if you expect t to be small. If t can be large you should use one of the other solutions.
| Python function parameter: tuple/list | My function expects a list or a tuple as a parameter. It doesn't really care which it is, all it does is pass it to another function that accepts either a list or tuple:
def func(arg): # arg is tuple or list
another_func(x)
# do other stuff here
Now I need to modify the function slightly, to process an additional element:
def func(arg): #arg is tuple or list
another_func(x + ['a'])
# etc
Unfortunately this is not going to work: if arg is tuple, I must say x + ('a',).
Obviously, I can make it work by coercing arg to list. But it isn't neat.
Is there a better way of doing that? I can't force callers to always pass a tuple, of course, since it simply shifts to work to them.
| [
"If another_func just wants a iterable you can pass itertools.chain(x,'a') to it.\n",
"What about changing the other function to accept a list of params instead ?\ndef func(arg): # arg is tuple or list\n another_func('a', *x)\n\n",
"how about:\nl = ['a']\nl.extend(x)\n\nEdit:\nRe-reading question, I think this... | [
7,
4,
3,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"coding_style",
"list",
"python",
"tuples"
] | stackoverflow_0004208619_coding_style_list_python_tuples.txt |
Q:
what is wrong with my system, unable to unpack dict. having unicode objects?
In [1]: l1 = lambda *args, **kw: args
In [2]: l1(**{'name':'hello'})
Out[2]: ()
In [3]: l1(**{u'name':'hello'})
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/sma/<ipython console> in <module>()
I've some problem with Python unable to pass/unpack the dictionary elements to the functions... might be my python is corrupted or system is broken don't know but this is strange
I'm using
python 2.6.2 on Ubuntu 9.04 Jaunty Jacob
A:
Seems to be related with this (non-)bug (old), but there are even more bug reports and it really seems to be fixed from 2.6.5 on only.
That is all I found and I don't have more insight into Python to explain how or why ;)
| what is wrong with my system, unable to unpack dict. having unicode objects? | In [1]: l1 = lambda *args, **kw: args
In [2]: l1(**{'name':'hello'})
Out[2]: ()
In [3]: l1(**{u'name':'hello'})
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/sma/<ipython console> in <module>()
I've some problem with Python unable to pass/unpack the dictionary elements to the functions... might be my python is corrupted or system is broken don't know but this is strange
I'm using
python 2.6.2 on Ubuntu 9.04 Jaunty Jacob
| [
"Seems to be related with this (non-)bug (old), but there are even more bug reports and it really seems to be fixed from 2.6.5 on only.\nThat is all I found and I don't have more insight into Python to explain how or why ;)\n"
] | [
2
] | [] | [] | [
"argument_unpacking",
"dictionary",
"python",
"ubuntu"
] | stackoverflow_0004213245_argument_unpacking_dictionary_python_ubuntu.txt |
Q:
lxml build on Solaris 10
Please can you help and advise with a problem with python 2.6.6 and lxml Solaris 10 build?
Installation instructions:
www.sunfreeware.com/download.html
direct link to the file:
http://www.sunfreeware.com/ftp/pub/freeware/sparc/10/lxml-2.2.8-sol10-sparc-local.gz
[rainier]/usr/apps/openet/bmsystest/relAuto/RAP_SW> python
Python 2.6.6 (r266:84292, Oct 12 2010, 15:25:47) [C] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml
>>> from lxml import etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: ld.so.1: python: fatal: relocation error: file /opt/csw/lib/python/site-packages/lxml-2.2.8-py2.6-solaris-2.10-sun4u.egg/lxml/etree.so: symbol xsltDocDefaultLoader: referenced symbol not found
>>>
Thanks
Mismatch of version: this is identical to the advise I got independently and I can only pass it onto the installer as I am developer and do not have root privilege.
Thanks for such a quick response!
A:
I've seen this before. Think it was due to a mismatch between two versions of python.
I think it was that python was calling /usr/local/bin/python, but lxml had compiled against a different version of python (found in /bin/python or something like that)
| lxml build on Solaris 10 | Please can you help and advise with a problem with python 2.6.6 and lxml Solaris 10 build?
Installation instructions:
www.sunfreeware.com/download.html
direct link to the file:
http://www.sunfreeware.com/ftp/pub/freeware/sparc/10/lxml-2.2.8-sol10-sparc-local.gz
[rainier]/usr/apps/openet/bmsystest/relAuto/RAP_SW> python
Python 2.6.6 (r266:84292, Oct 12 2010, 15:25:47) [C] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml
>>> from lxml import etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: ld.so.1: python: fatal: relocation error: file /opt/csw/lib/python/site-packages/lxml-2.2.8-py2.6-solaris-2.10-sun4u.egg/lxml/etree.so: symbol xsltDocDefaultLoader: referenced symbol not found
>>>
Thanks
Mismatch of version: this is identical to the advise I got independently and I can only pass it onto the installer as I am developer and do not have root privilege.
Thanks for such a quick response!
| [
"I've seen this before. Think it was due to a mismatch between two versions of python. \nI think it was that python was calling /usr/local/bin/python, but lxml had compiled against a different version of python (found in /bin/python or something like that)\n"
] | [
3
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0004211680_lxml_python.txt |
Q:
what do %(xyz)s representation mean in python
What are these representation in python and how to use. My guess is it is used for data validation but never able to use it.
%(name)s
%(levelno)s
%(levelname)s
%(pathname)s
%(process)d
etc..
A:
This is string formatting using keys:
>>> d = {"answer": 42}
>>> "the answer is %(answer)d" % d
'the answer is 42'
A:
It's formatting a string, by picking values from a dictionary:
test = { "foo": 48, "bar": 4711, "hello": "yes" }
print "%(foo)d %(bar)d and %(hello)s" % test
prints:
48 4711 and yes
| what do %(xyz)s representation mean in python | What are these representation in python and how to use. My guess is it is used for data validation but never able to use it.
%(name)s
%(levelno)s
%(levelname)s
%(pathname)s
%(process)d
etc..
| [
"This is string formatting using keys:\n>>> d = {\"answer\": 42}\n>>> \"the answer is %(answer)d\" % d\n'the answer is 42'\n\n",
"It's formatting a string, by picking values from a dictionary:\ntest = { \"foo\": 48, \"bar\": 4711, \"hello\": \"yes\" }\nprint \"%(foo)d %(bar)d and %(hello)s\" % test\n\nprints:\n4... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0004213559_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.