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:
Upload a potentially huge textfile to a plain WSGI-server in Python
I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible.
A:
wsgi.input should be a file like stream object. You can read from that in blocks, and write those blocks directly to disk. That shouldn't use up any significant memory.
Or maybe I misunderstood the question?
A:
If you use the cgi module to parse the input (which most frameworks use, e.g., Pylons, WebOb, CherryPy) then it will automatically save the uploaded file to a temporary file, and not load it into memory.
A:
Has python know how to deal with gzip annd zip file I would suggest you to compress your file (using a zip or gzip compliant application like 7-zip) on your client and then upload it to your server.
Even better : write a script that automaticaly compress your file and upload it. This is possible with the standard library.
|
Upload a potentially huge textfile to a plain WSGI-server in Python
|
I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible.
|
[
"wsgi.input should be a file like stream object. You can read from that in blocks, and write those blocks directly to disk. That shouldn't use up any significant memory.\nOr maybe I misunderstood the question?\n",
"If you use the cgi module to parse the input (which most frameworks use, e.g., Pylons, WebOb, CherryPy) then it will automatically save the uploaded file to a temporary file, and not load it into memory.\n",
"Has python know how to deal with gzip annd zip file I would suggest you to compress your file (using a zip or gzip compliant application like 7-zip) on your client and then upload it to your server.\nEven better : write a script that automaticaly compress your file and upload it. This is possible with the standard library.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"file",
"python",
"upload",
"wsgi"
] |
stackoverflow_0001103940_file_python_upload_wsgi.txt
|
Q:
python web programming
I started learning Python through some books and online tutorials. I understand the basic syntax and operations, but I realize that the correct way to understand the language would be to actually do a project on it.
Now when i say a project, I mean something useful, maybe some web app. I started searching for web programming in python and landed on a couple of tutorials referencing a very complex code. most of it was based upon, i think, CGI programming.
now what i would really appreciate is if someone could provide certain guidelines on how a beginner like me can understand the various aspects of programming the web through python. because the things i am seeing are just confusing me. can anyone please help?
A:
+1 for django, though the "django book" is a little simpler to understand (especially if you're just getting start with python): http://www.djangobook.com/en/2.0/
A:
If you want to create a powerful web application with Python, Django is the way to go. You can start with the documentation at http://docs.djangoproject.com/en/dev/ or the Django Book (I recommend the latter). It's a bit complicated to grasp as a beginner, but it's totally worth the hassle :)
Good Luck!
A:
Start with the Django tutorial here http://docs.djangoproject.com/en/dev/intro/tutorial01/ and work your way to the end, then go back and read the rest of the Django documentation.
A:
Google App Engine uses python and runs on Google's infrastructure: http://code.google.com/appengine/
They have many tutorials and examples that can help you get started.
A:
Start by writing really simple network application.
Try starting with a small program that listens on a port, and gives some status message when questioned. For example, when a web browser calls it, It would display the time and some facts about the system.
That would tech you the basics, and you'll find your route from there on.
EDIT:
Begin with Making a simple web server in Python. If you want to learn some theoretical background, try the legendary Beej's Guide to Network Programming. The examples are in C, but it'll get you through terms like socket, bind, port and listen.
If you're unhappy with the tutorial I have given above, Just Google "Python server" or "Python network tutorial" and you'll find lots of them.
A:
You can read substantial parts of "Python in a Nutshell" for free online -- though selective pages are being omitted at the publisher's request to induce you to buy the book -- and other only partly-overlapping parts of the second edition here. The chapters I'm pointing you to in both the first and second editions are about sockets and server-side network programming, the immediately previous ones cover network and web programming with a focus on the client sides, and following ones cover CGI and alternatives, HTML, XML, etc.
Not covered, due to the age of the books, is the best alternative to CGI, WSGI (can actually be deployed on top of CGI, but also very efficiently on Apache, nginx, Google App Engine, etc; and basically all modern Python web frameworks run well on top of WSGI -- there are also some highly modular "not quite frameworks" such as werkzeug that are totally WSGI-focused).
To deliver a working Python web app ASAP, Django is probably the best and definitely the most popular choice today; but the very aspects that make it such a high-productivity environment (the huge amount of things it does "hiddenly and magically" on your behalf) make it less useful for pure learning purposes than more modular, less abstract, less magical frameworks such as Paste, Pylons, Werkzeug, &c. It's very instructive to start on plain WSGI and add helpful components and middleware only gradually as you understand why they're better than doing it all yourself "by hand".
For more info on WSGI, see its own site which is rich with helpful links & docs.
A:
There are many web frameworks for Python.
The most popular is Django, but don't believe the people here that it is "the only way" or similar. They simply haven't used any other.
Django is a good full stack framework. http://www.djangoproject.com/
But so is Turbogears, which is full stack by means of putting different parts together, so it's less monolithic. http://turbogears.org/
And if you want a really massive über-full-stack framework look at Grok. http://grok.zope.org/
If you on the other hand want something minimalistic, there is Pylons (which is used by Turbogears etc) http://pylonshq.com/
Or the new hot thing: BFG. http://bfg.repoze.org/
Look around to see what you want, read the tutorials to see what makes sense to you. And if you can't make up your mind, then go for Django. :-)
A:
If you start with Appengine (Django, webapp, DIY with WebOb, Pylons -- whatever) then if you get an application written, no matter how stupid or trivial, you can deploy it and it'll keep working and you can share it with people. The whole deploy-and-keep-working task is largely unrelated to programming or Python, but it's also a lot of work. By skipping that you can focus on the programming and have the motivation of making real deployed applications.
|
python web programming
|
I started learning Python through some books and online tutorials. I understand the basic syntax and operations, but I realize that the correct way to understand the language would be to actually do a project on it.
Now when i say a project, I mean something useful, maybe some web app. I started searching for web programming in python and landed on a couple of tutorials referencing a very complex code. most of it was based upon, i think, CGI programming.
now what i would really appreciate is if someone could provide certain guidelines on how a beginner like me can understand the various aspects of programming the web through python. because the things i am seeing are just confusing me. can anyone please help?
|
[
"+1 for django, though the \"django book\" is a little simpler to understand (especially if you're just getting start with python): http://www.djangobook.com/en/2.0/\n",
"If you want to create a powerful web application with Python, Django is the way to go. You can start with the documentation at http://docs.djangoproject.com/en/dev/ or the Django Book (I recommend the latter). It's a bit complicated to grasp as a beginner, but it's totally worth the hassle :)\nGood Luck!\n",
"Start with the Django tutorial here http://docs.djangoproject.com/en/dev/intro/tutorial01/ and work your way to the end, then go back and read the rest of the Django documentation.\n",
"Google App Engine uses python and runs on Google's infrastructure: http://code.google.com/appengine/\nThey have many tutorials and examples that can help you get started.\n",
"Start by writing really simple network application.\nTry starting with a small program that listens on a port, and gives some status message when questioned. For example, when a web browser calls it, It would display the time and some facts about the system.\nThat would tech you the basics, and you'll find your route from there on.\nEDIT:\nBegin with Making a simple web server in Python. If you want to learn some theoretical background, try the legendary Beej's Guide to Network Programming. The examples are in C, but it'll get you through terms like socket, bind, port and listen.\nIf you're unhappy with the tutorial I have given above, Just Google \"Python server\" or \"Python network tutorial\" and you'll find lots of them.\n",
"You can read substantial parts of \"Python in a Nutshell\" for free online -- though selective pages are being omitted at the publisher's request to induce you to buy the book -- and other only partly-overlapping parts of the second edition here. The chapters I'm pointing you to in both the first and second editions are about sockets and server-side network programming, the immediately previous ones cover network and web programming with a focus on the client sides, and following ones cover CGI and alternatives, HTML, XML, etc.\nNot covered, due to the age of the books, is the best alternative to CGI, WSGI (can actually be deployed on top of CGI, but also very efficiently on Apache, nginx, Google App Engine, etc; and basically all modern Python web frameworks run well on top of WSGI -- there are also some highly modular \"not quite frameworks\" such as werkzeug that are totally WSGI-focused).\nTo deliver a working Python web app ASAP, Django is probably the best and definitely the most popular choice today; but the very aspects that make it such a high-productivity environment (the huge amount of things it does \"hiddenly and magically\" on your behalf) make it less useful for pure learning purposes than more modular, less abstract, less magical frameworks such as Paste, Pylons, Werkzeug, &c. It's very instructive to start on plain WSGI and add helpful components and middleware only gradually as you understand why they're better than doing it all yourself \"by hand\".\nFor more info on WSGI, see its own site which is rich with helpful links & docs.\n",
"There are many web frameworks for Python.\nThe most popular is Django, but don't believe the people here that it is \"the only way\" or similar. They simply haven't used any other. \n\nDjango is a good full stack framework. http://www.djangoproject.com/\nBut so is Turbogears, which is full stack by means of putting different parts together, so it's less monolithic. http://turbogears.org/\nAnd if you want a really massive über-full-stack framework look at Grok. http://grok.zope.org/\nIf you on the other hand want something minimalistic, there is Pylons (which is used by Turbogears etc) http://pylonshq.com/\nOr the new hot thing: BFG. http://bfg.repoze.org/\n\nLook around to see what you want, read the tutorials to see what makes sense to you. And if you can't make up your mind, then go for Django. :-)\n",
"If you start with Appengine (Django, webapp, DIY with WebOb, Pylons -- whatever) then if you get an application written, no matter how stupid or trivial, you can deploy it and it'll keep working and you can share it with people. The whole deploy-and-keep-working task is largely unrelated to programming or Python, but it's also a lot of work. By skipping that you can focus on the programming and have the motivation of making real deployed applications.\n"
] |
[
6,
4,
2,
2,
2,
2,
0,
0
] |
[] |
[] |
[
"python",
"web_applications"
] |
stackoverflow_0001209092_python_web_applications.txt
|
Q:
Dictionary with classes?
In Python is it possible to instantiate a class through a dictionary?
shapes = {'1':Square(), '2':Circle(), '3':Triangle()}
x = shapes[raw_input()]
I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of Circle. Is this possible?
A:
Almost. What you want is
shapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict
x = shapes[raw_input()]() # get class from dict, then call it to create a shape instance.
A:
I'd recommend a chooser function:
def choose(optiondict, prompt='Choose one:'):
print prompt
while 1:
for key, value in sorted(optiondict.items()):
print '%s) %s' % (key, value)
result = raw_input() # maybe with .lower()
if result in optiondict:
return optiondict[result]
print 'Not an option'
result = choose({'1': Square, '2': Circle, '3': Triangle})()
|
Dictionary with classes?
|
In Python is it possible to instantiate a class through a dictionary?
shapes = {'1':Square(), '2':Circle(), '3':Triangle()}
x = shapes[raw_input()]
I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of Circle. Is this possible?
|
[
"Almost. What you want is\nshapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict\n\nx = shapes[raw_input()]() # get class from dict, then call it to create a shape instance.\n\n",
"I'd recommend a chooser function:\ndef choose(optiondict, prompt='Choose one:'):\n print prompt\n while 1:\n for key, value in sorted(optiondict.items()):\n print '%s) %s' % (key, value)\n result = raw_input() # maybe with .lower()\n if result in optiondict:\n return optiondict[result]\n print 'Not an option'\n\nresult = choose({'1': Square, '2': Circle, '3': Triangle})()\n\n"
] |
[
30,
2
] |
[] |
[] |
[
"class",
"dictionary",
"python"
] |
stackoverflow_0001208322_class_dictionary_python.txt
|
Q:
How to find number of users, number of users with a profile object, and monthly logins in Django
Is there an easy way in Django to find the number of Users, Number of Users with profile objects, and ideally number of logins per month (but could do this with Google Analytics). I can see all the data is there in the admin interface, but I'm unsure of how to get to it in Python land. Has anyone seen any examples of counting number of user objects?
A:
Count the number of users:
import django.contrib.auth
django.contrib.auth.models.User.objects.all().count()
You can use the same to count the number of profile objects (assuming every user has at most 1 profile), e.g. if Profile is the profile model:
Profile.objects.all().count()
To count the number of logins in a month you'd need to create a table logging each login with a time stamp. Then it's a matter of using count() again.
|
How to find number of users, number of users with a profile object, and monthly logins in Django
|
Is there an easy way in Django to find the number of Users, Number of Users with profile objects, and ideally number of logins per month (but could do this with Google Analytics). I can see all the data is there in the admin interface, but I'm unsure of how to get to it in Python land. Has anyone seen any examples of counting number of user objects?
|
[
"Count the number of users:\nimport django.contrib.auth\ndjango.contrib.auth.models.User.objects.all().count()\n\nYou can use the same to count the number of profile objects (assuming every user has at most 1 profile), e.g. if Profile is the profile model:\nProfile.objects.all().count()\n\nTo count the number of logins in a month you'd need to create a table logging each login with a time stamp. Then it's a matter of using count() again.\n"
] |
[
1
] |
[] |
[] |
[
"admin",
"django",
"python"
] |
stackoverflow_0001210099_admin_django_python.txt
|
Q:
Formatting text into boxes in the Python Shell
I've created a basic menu class that looks like this:
class Menu:
def __init__(self, title, body):
self.title = title
self.body = body
def display(self):
#print the menu to the screen
What I want to do is format the title and the body so they fit inside premade boxes almost. Where no matter what I pass as the body, display will be able to fit it inside. The format would look something like this.
********************************************************************************
* Here's the title *
********************************************************************************
* *
* The body will go in here. Say I put a line break here ---> \n *
* it will go to the next line. I also want to keep track\n *
* \t <----- of tabs so I can space things out on lines if i have to *
* *
********************************************************************************
The title I think will be easy but I'm getting lost on the body.
A:
#!/usr/bin/env python
def format_box(title, body, width=80):
box_line = lambda text: "* " + text + (" " * (width - 6 - len(text))) + " *"
print "*" * width
print box_line(title)
print "*" * width
print box_line("")
for line in body.split("\n"):
print box_line(line.expandtabs())
print box_line("")
print "*" * width
format_box(
"Here's the title",
"The body will go in here. Say I put a line break here ---> \n"
"it will go to the next line. I also want to keep track\n"
"\t<----- of tabs so I can space things out on lines if i have to"
);
A:
You could also try the standard 'textwrap' module
|
Formatting text into boxes in the Python Shell
|
I've created a basic menu class that looks like this:
class Menu:
def __init__(self, title, body):
self.title = title
self.body = body
def display(self):
#print the menu to the screen
What I want to do is format the title and the body so they fit inside premade boxes almost. Where no matter what I pass as the body, display will be able to fit it inside. The format would look something like this.
********************************************************************************
* Here's the title *
********************************************************************************
* *
* The body will go in here. Say I put a line break here ---> \n *
* it will go to the next line. I also want to keep track\n *
* \t <----- of tabs so I can space things out on lines if i have to *
* *
********************************************************************************
The title I think will be easy but I'm getting lost on the body.
|
[
"#!/usr/bin/env python\n\ndef format_box(title, body, width=80):\n box_line = lambda text: \"* \" + text + (\" \" * (width - 6 - len(text))) + \" *\"\n\n print \"*\" * width\n print box_line(title)\n print \"*\" * width\n print box_line(\"\")\n\n for line in body.split(\"\\n\"):\n print box_line(line.expandtabs())\n\n print box_line(\"\")\n print \"*\" * width\n\nformat_box(\n \"Here's the title\",\n\n \"The body will go in here. Say I put a line break here ---> \\n\"\n \"it will go to the next line. I also want to keep track\\n\"\n \"\\t<----- of tabs so I can space things out on lines if i have to\"\n);\n\n",
"You could also try the standard 'textwrap' module\n"
] |
[
4,
0
] |
[] |
[] |
[
"formatting",
"python",
"shell"
] |
stackoverflow_0001203036_formatting_python_shell.txt
|
Q:
outer join modelisation in django
I have a many to many relationship table whith some datas in the jointing base
a basic version of my model look like:
class FooLine(models.Model):
name = models.CharField(max_length=255)
class FooCol(models.Model):
name = models.CharField(max_length=255)
class FooVal(models.Model):
value = models.CharField(max_length=255)
line = models.ForeignKey(FooLine)
col = models.ForeignKey(FooCol)
I'm trying to search every values for a certain line with a null if the value is not present (basically i'm trying to display the fooval table with null values for values that haven't been filled)
a typical sql would be
SELECT value FROM FooCol LEFT OUTER JOIN
(FooVal JOIN FooLine
ON FooVal.line_id == FooLine.id AND FooLine.name = "FIXME")
ON FooCol.id = col_id;
Is there any way to modelise above query using django model
Thanks
A:
Outer joins can be viewed as a hack because SQL lacks "navigation".
What you have is a simple if-statement situation.
for line in someRangeOfLines:
for col in someRangeOfCols:
try:
cell= FooVal.objects().get( col = col, line = line )
except FooVal.DoesNotExist:
cell= None
That's what an outer join really is -- an attempted lookup with a NULL replacement.
The only optimization is something like the following.
matrix = {}
for f in FooVal.objects().all():
matrix[(f.line,f.col)] = f
for line in someRangeOfLines:
for col in someRangeOfCols:
cell= matrix.get((line,col),None)
|
outer join modelisation in django
|
I have a many to many relationship table whith some datas in the jointing base
a basic version of my model look like:
class FooLine(models.Model):
name = models.CharField(max_length=255)
class FooCol(models.Model):
name = models.CharField(max_length=255)
class FooVal(models.Model):
value = models.CharField(max_length=255)
line = models.ForeignKey(FooLine)
col = models.ForeignKey(FooCol)
I'm trying to search every values for a certain line with a null if the value is not present (basically i'm trying to display the fooval table with null values for values that haven't been filled)
a typical sql would be
SELECT value FROM FooCol LEFT OUTER JOIN
(FooVal JOIN FooLine
ON FooVal.line_id == FooLine.id AND FooLine.name = "FIXME")
ON FooCol.id = col_id;
Is there any way to modelise above query using django model
Thanks
|
[
"Outer joins can be viewed as a hack because SQL lacks \"navigation\". \nWhat you have is a simple if-statement situation.\nfor line in someRangeOfLines:\n for col in someRangeOfCols:\n try:\n cell= FooVal.objects().get( col = col, line = line )\n except FooVal.DoesNotExist:\n cell= None\n\nThat's what an outer join really is -- an attempted lookup with a NULL replacement.\nThe only optimization is something like the following.\nmatrix = {}\nfor f in FooVal.objects().all():\n matrix[(f.line,f.col)] = f\n\nfor line in someRangeOfLines:\n for col in someRangeOfCols:\n cell= matrix.get((line,col),None)\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"outer_join",
"python",
"request"
] |
stackoverflow_0001209947_django_outer_join_python_request.txt
|
Q:
help me eliminate a for-loop in python
There has to be a faster way of doing this.
There is a lot going on here, but it's fairly straightforward to unpack.
Here is the relevant python code (from scipy import *)
for i in arange(len(wav)):
result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) )
There are a bunch of arrays.
result -- array of length (wav)
laser_flux -- array of length (laser)
wav -- array of length (wav)
laser_wav -- array of length (laser)
Yes, within the exponential, I am squaring (element by element) the difference between the scalar value and the array of laser_wav.
Everything works as expected (including SLOWLY) any help you can give me to eliminate this for-loop would be much appreciated!
A:
You're going to want to use Numpy arrays (if you're not already) to store your data. Then, you can take advantage of array broadcasting with np.newaxis. For each value in wav, you're going to want to compute a difference between that value and each value in laser_wav. That suggests that you'll want a two-dimensional array, with the two dimensions being the wav dimension and the laser dimension.
In the example below, I'll pick the first index as the laser index and the second index as the wav index. With sample data, this becomes:
import numpy as np
LASER_LEN = 5
WAV_LEN = 10
laser_flux = np.arange(LASER_LEN)
wav = np.arange(WAV_LEN)
laser_wav = np.array(LASER_LEN)
# Tile wav into LASER_LEN rows and tile laser_wav into WAV_LEN columns
diff = wav[np.newaxis,:] - laser_wav[:,np.newaxis]
exp_arg = -diff ** 2
sum_arg = laser_flux[:,np.newaxis] * np.exp(exp_arg)
# Now, the resulting array sum_arg should be of size (LASER_LEN,WAV_LEN)
# Since your original sum was along each element of laser_flux/laser_wav,
# you'll need to sum along the first axis.
result = np.sum(sum_arg, axis=0)
Of course, you could just condense this down into a single statement:
result = np.sum(laser_flux[:,np.newaxis] *
np.exp(-(wav[np.newaxis,:]-laser_wav[:,np.newaxis])**2),axis=0)
Edit:
As noted in the comments to the question, you can take advantage of the "sum of multiplications" inherent in the definition of linear-algebra style multiplications. This then becomes:
result = np.dot(laser_flux,
np.exp(-(wav[np.newaxis,:] - laser_wav[:,np.newaxis])**2))
A:
I'm new to Python, so this may not the most optimal in Python, but I'd use the same technique for Perl, Scheme, etc.
def func(x):
delta = x - laser_wav
return sum(laser_flux * exp(-delta * delta))
result = map(func, wav)
A:
If raw performance is an issue, you might benefit from rewriting to take advantage of multiple cores, if you have them.
from multiprocessing import Pool
p = Pool(5) # about the number of cores you have
def f(i):
delta = wav[i] - laser_wav
return sum(laser_flux * exp(-delta*delta) )
result = p.map(f, arange(len(wav)) )
A:
For one thing, it seems to be slightly quicker to multiply a variable by itself than to use the ** power operator:
~$ python -m timeit -n 100000 -v "x = 4.1; x * x"
raw times: 0.0904 0.0513 0.0493
100000 loops, best of 3: 0.493 usec per loop
~$ python -m timeit -n 100000 -v "x = 4.1; x**2"
raw times: 0.101 0.147 0.118
100000 loops, best of 3: 1.01 usec per loop
|
help me eliminate a for-loop in python
|
There has to be a faster way of doing this.
There is a lot going on here, but it's fairly straightforward to unpack.
Here is the relevant python code (from scipy import *)
for i in arange(len(wav)):
result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) )
There are a bunch of arrays.
result -- array of length (wav)
laser_flux -- array of length (laser)
wav -- array of length (wav)
laser_wav -- array of length (laser)
Yes, within the exponential, I am squaring (element by element) the difference between the scalar value and the array of laser_wav.
Everything works as expected (including SLOWLY) any help you can give me to eliminate this for-loop would be much appreciated!
|
[
"You're going to want to use Numpy arrays (if you're not already) to store your data. Then, you can take advantage of array broadcasting with np.newaxis. For each value in wav, you're going to want to compute a difference between that value and each value in laser_wav. That suggests that you'll want a two-dimensional array, with the two dimensions being the wav dimension and the laser dimension. \nIn the example below, I'll pick the first index as the laser index and the second index as the wav index. With sample data, this becomes:\nimport numpy as np\n\nLASER_LEN = 5\nWAV_LEN = 10\nlaser_flux = np.arange(LASER_LEN)\nwav = np.arange(WAV_LEN)\nlaser_wav = np.array(LASER_LEN)\n\n# Tile wav into LASER_LEN rows and tile laser_wav into WAV_LEN columns\ndiff = wav[np.newaxis,:] - laser_wav[:,np.newaxis]\nexp_arg = -diff ** 2\nsum_arg = laser_flux[:,np.newaxis] * np.exp(exp_arg)\n\n# Now, the resulting array sum_arg should be of size (LASER_LEN,WAV_LEN)\n# Since your original sum was along each element of laser_flux/laser_wav, \n# you'll need to sum along the first axis.\nresult = np.sum(sum_arg, axis=0)\n\nOf course, you could just condense this down into a single statement:\nresult = np.sum(laser_flux[:,np.newaxis] * \n np.exp(-(wav[np.newaxis,:]-laser_wav[:,np.newaxis])**2),axis=0)\n\nEdit:\nAs noted in the comments to the question, you can take advantage of the \"sum of multiplications\" inherent in the definition of linear-algebra style multiplications. This then becomes:\nresult = np.dot(laser_flux, \n np.exp(-(wav[np.newaxis,:] - laser_wav[:,np.newaxis])**2))\n\n",
"I'm new to Python, so this may not the most optimal in Python, but I'd use the same technique for Perl, Scheme, etc.\ndef func(x):\n delta = x - laser_wav\n return sum(laser_flux * exp(-delta * delta))\nresult = map(func, wav)\n\n",
"If raw performance is an issue, you might benefit from rewriting to take advantage of multiple cores, if you have them. \nfrom multiprocessing import Pool\np = Pool(5) # about the number of cores you have\n\ndef f(i):\n delta = wav[i] - laser_wav\n return sum(laser_flux * exp(-delta*delta) )\n\nresult = p.map(f, arange(len(wav)) )\n\n",
"For one thing, it seems to be slightly quicker to multiply a variable by itself than to use the ** power operator:\n~$ python -m timeit -n 100000 -v \"x = 4.1; x * x\"\nraw times: 0.0904 0.0513 0.0493\n100000 loops, best of 3: 0.493 usec per loop\n~$ python -m timeit -n 100000 -v \"x = 4.1; x**2\"\nraw times: 0.101 0.147 0.118\n100000 loops, best of 3: 1.01 usec per loop\n\n"
] |
[
13,
2,
1,
0
] |
[] |
[] |
[
"for_loop",
"python"
] |
stackoverflow_0001210509_for_loop_python.txt
|
Q:
usage of generators as a progression notifier
I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant...
Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction, etc) which takes a lot of time (from seconds to several minutes).
I use this module from a GUI written in wxpython and a console script.
When I looked at how to implement progress dialogs in wxpython, I saw that I must get somehow a progress value to update my dialog, which is pure logic you'll admit...
So I decided to use the number of frame processed in my engine functions, yield the current frame number every 33 frames and yield None when the processing is finished.
by doing that here's what it looks like:
dlg = wx.ProgressDialog("Movie processing", "Movie is being written...",
maximum = self.engine.endProcessingFrame,self.engine.startProcessingFrame,
parent=self,
style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_SMOOTH | wx.PD_CAN_ABORT)
state = self.engine.processMovie()
f = state.next()
while f != None:
c, s = dlg.Update(f, "Processing frame %d"%f)
if not c:break
f = state.next()
dlg.Destroy()
That works very well, there is absolutely no noticeable speed loss, but I would like to be able to call processMovie() function without having to deal with generators if I don't want to.
For instance my console script which uses the engine module doesn't care of the progress, I could use it but it is destined to be executed in an environment where there is no display so I really don't care about the progress...
Anyone with another design that the one I came up with? (using threads, globals, processes, etc)
There must be a design somewhere that does this job cleany I think :-)
A:
Using a generator is fine for this, but the whole point of using generators is so you can builtin syntax:
for f in self.engine.processMovie():
c, s = dlg.Update(f, "Processing frame %d"%f)
if not c: break
If you don't care about that, then you can either say:
for f in self.engine.processMovie(): pass
or expose a function (eg. engine.processMovieFull) to do that for you.
You could also use a plain callback:
def update_state(f):
c, s = dlg.Update(f, "Processing frame %d"%f)
return c
self.engine.processMovie(progress=update_state)
... but that's not as nice if you want to process the data piecemeal; callback models prefer to do all the work at once--that's the real benefit of generators.
A:
This sounds like a perfect case for events. The process sends a "status update event", and anyone who wants to know (in this case the dialog) listens to that event.
A:
First of all, if you use a generator, you might as well use it as an iterator:
state = self.engine.processMovie()
for f in state:
c, s = dlg.Update(f, "Processing frame %d"%f)
if not c:
break
dlg.Destroy()
And don't yield None; stop yielding when you're done and leave the function; alternatively raise StopIteration. This is the correct way of ending generation (and when using a for loop, it's necessary).
Other than that, I like the idea. In my opinion, this is a very valid use of generators.
You might want to make the 33 configurable (i.e. passable to processMovie as a parameter); 33 seems like an arbitrary choice, and if your process a two-hour movie, there's no need to update the progress bar every 33 frames I guess.
|
usage of generators as a progression notifier
|
I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant...
Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction, etc) which takes a lot of time (from seconds to several minutes).
I use this module from a GUI written in wxpython and a console script.
When I looked at how to implement progress dialogs in wxpython, I saw that I must get somehow a progress value to update my dialog, which is pure logic you'll admit...
So I decided to use the number of frame processed in my engine functions, yield the current frame number every 33 frames and yield None when the processing is finished.
by doing that here's what it looks like:
dlg = wx.ProgressDialog("Movie processing", "Movie is being written...",
maximum = self.engine.endProcessingFrame,self.engine.startProcessingFrame,
parent=self,
style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_SMOOTH | wx.PD_CAN_ABORT)
state = self.engine.processMovie()
f = state.next()
while f != None:
c, s = dlg.Update(f, "Processing frame %d"%f)
if not c:break
f = state.next()
dlg.Destroy()
That works very well, there is absolutely no noticeable speed loss, but I would like to be able to call processMovie() function without having to deal with generators if I don't want to.
For instance my console script which uses the engine module doesn't care of the progress, I could use it but it is destined to be executed in an environment where there is no display so I really don't care about the progress...
Anyone with another design that the one I came up with? (using threads, globals, processes, etc)
There must be a design somewhere that does this job cleany I think :-)
|
[
"Using a generator is fine for this, but the whole point of using generators is so you can builtin syntax:\nfor f in self.engine.processMovie():\n c, s = dlg.Update(f, \"Processing frame %d\"%f)\n if not c: break\n\nIf you don't care about that, then you can either say:\nfor f in self.engine.processMovie(): pass\n\nor expose a function (eg. engine.processMovieFull) to do that for you.\nYou could also use a plain callback:\ndef update_state(f):\n c, s = dlg.Update(f, \"Processing frame %d\"%f)\n return c\nself.engine.processMovie(progress=update_state)\n\n... but that's not as nice if you want to process the data piecemeal; callback models prefer to do all the work at once--that's the real benefit of generators.\n",
"This sounds like a perfect case for events. The process sends a \"status update event\", and anyone who wants to know (in this case the dialog) listens to that event.\n",
"First of all, if you use a generator, you might as well use it as an iterator:\nstate = self.engine.processMovie()\n\nfor f in state:\n c, s = dlg.Update(f, \"Processing frame %d\"%f)\n if not c:\n break\n\ndlg.Destroy()\n\nAnd don't yield None; stop yielding when you're done and leave the function; alternatively raise StopIteration. This is the correct way of ending generation (and when using a for loop, it's necessary).\nOther than that, I like the idea. In my opinion, this is a very valid use of generators.\nYou might want to make the 33 configurable (i.e. passable to processMovie as a parameter); 33 seems like an arbitrary choice, and if your process a two-hour movie, there's no need to update the progress bar every 33 frames I guess.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"generator",
"progress_bar",
"python"
] |
stackoverflow_0001211035_generator_progress_bar_python.txt
|
Q:
downloading files to users machine?
I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to.
any ideas?
A:
You can't forcefully download files to a user without his consent. If that was possible you can only imagine what severe security flaw that would be.
You can do one of two things:
count on the browser to cache the media file
serve the media via some 3rd party plugin (Flash, for example)
A:
Don't do this.
Most files are cached anyway.
But if you really want to add this (because users asked for it), make it optional (default off).
A:
I have no experience with this, but you could try your luck with DOM storage in newer browsers:
IE8
FF>=2
Opera > 9.5, as I have read somewhere
Safari and Chrome should implement it, too, I guess
Here's an article by John Resig about that.
However, if questions contain something like 'without the user's knowledge' or 'without the user having to agree', typically the one asking really should reconsider his/her thoughts about the visitors and what is or isn't good for them.
Cheers,
|
downloading files to users machine?
|
I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to.
any ideas?
|
[
"You can't forcefully download files to a user without his consent. If that was possible you can only imagine what severe security flaw that would be.\nYou can do one of two things:\n\ncount on the browser to cache the media file\nserve the media via some 3rd party plugin (Flash, for example)\n\n",
"Don't do this.\nMost files are cached anyway.\nBut if you really want to add this (because users asked for it), make it optional (default off).\n",
"I have no experience with this, but you could try your luck with DOM storage in newer browsers:\n\nIE8\nFF>=2\nOpera > 9.5, as I have read somewhere\nSafari and Chrome should implement it, too, I guess\n\nHere's an article by John Resig about that.\nHowever, if questions contain something like 'without the user's knowledge' or 'without the user having to agree', typically the one asking really should reconsider his/her thoughts about the visitors and what is or isn't good for them.\nCheers,\n"
] |
[
4,
2,
0
] |
[] |
[] |
[
"django",
"python",
"web_applications"
] |
stackoverflow_0001211363_django_python_web_applications.txt
|
Q:
Django .."join" query?
guys, how or where is the "join" query in Django?
i think that Django dont have "join"..but how ill make join?
Thanks
A:
If you're using models, the select_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model.
A:
Look into model relationships and accessing related objects.
|
Django .."join" query?
|
guys, how or where is the "join" query in Django?
i think that Django dont have "join"..but how ill make join?
Thanks
|
[
"If you're using models, the select_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model.\n",
"Look into model relationships and accessing related objects.\n"
] |
[
4,
1
] |
[
"SQL Join queries are a hack because SQL doesn't have objects or navigation among objects.\nObjects don't need \"joins\". Just access the related objects.\n"
] |
[
-10
] |
[
"django",
"python"
] |
stackoverflow_0001210711_django_python.txt
|
Q:
Moving values but preserving order in a Python list
I have a list
a=[1,2,3,4,5]
and want to 'move' its values so it changes into
a=[2,3,4,5,1]
and the next step
a=[3,4,5,1,2]
Is there a built-in function in Python to do that?
Or is there a shorter or nicer way than
b=[a[-1]]; b.extend(a[:-1]); a=b
A:
>>> a = [1,2,3,4,5]
>>> a.append(a.pop(0))
>>> a
[2, 3, 4, 5, 1]
This is expensive, though, as it has to shift the contents of the entire list, which is O(n). A better choice may be to use collections.deque if it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:
>>> a = collections.deque([1,2,3,4,5])
>>> a
deque([1, 2, 3, 4, 5])
>>> a.rotate(-1)
>>> a
deque([2, 3, 4, 5, 1])
Note also that both these solutions involve changing the original sequence object, whereas yours creates a new list and assigns it to a. So if we did:
>>> c = a
>>> # rotate a
With your method, c would continue to refer to the original, unrotated list, and with my methods, it will refer to the updated, rotated list/deque.
|
Moving values but preserving order in a Python list
|
I have a list
a=[1,2,3,4,5]
and want to 'move' its values so it changes into
a=[2,3,4,5,1]
and the next step
a=[3,4,5,1,2]
Is there a built-in function in Python to do that?
Or is there a shorter or nicer way than
b=[a[-1]]; b.extend(a[:-1]); a=b
|
[
">>> a = [1,2,3,4,5]\n>>> a.append(a.pop(0))\n>>> a\n[2, 3, 4, 5, 1]\n\nThis is expensive, though, as it has to shift the contents of the entire list, which is O(n). A better choice may be to use collections.deque if it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:\n>>> a = collections.deque([1,2,3,4,5])\n>>> a\ndeque([1, 2, 3, 4, 5])\n>>> a.rotate(-1)\n>>> a\ndeque([2, 3, 4, 5, 1])\n\nNote also that both these solutions involve changing the original sequence object, whereas yours creates a new list and assigns it to a. So if we did:\n>>> c = a\n>>> # rotate a\n\nWith your method, c would continue to refer to the original, unrotated list, and with my methods, it will refer to the updated, rotated list/deque.\n"
] |
[
25
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001212025_list_python.txt
|
Q:
m2crypto throws "TypeError: in method 'x509_req_set_pubkey'"
My little code snippet throws the following Traceback:
Traceback (most recent call last):
File "csr.py", line 48, in <module>
csr.create_cert_signing_request(pubkey, cert_name)
File "csr.py", line 17, in create_cert_signing_request
cert_request.set_pubkey(EVP.PKey(keypair))
File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey
return m2.x509_req_set_pubkey( self.req, pkey.pkey )
TypeError: in method 'x509_req_set_pubkey', argument 2 of type 'EVP_PKEY *'
Here are my two python modules:
from config import *
from keypair import *
from M2Crypto import X509
class CSR(object):
def __init__(self):
pass
def create_cert_signing_request(keypair, cert_name, cert_extension_stack=None):
# create a certificate signing request object
cert_request = X509.Request()
# set certificate version to 3
cert_request.set_version(3)
# which rsa public key should be used?
cert_request.set_pubkey(EVP.PKey(keypair))
# create an subject for the certificate request
cert_request.set_subject_name(cert_name)
if cert_extension_stack != None:
# add the extensions to the request
cert_request.add_extensions(cert_extension_stack)
# sign the request using the RSA key pair
cert_request.sign(keypair, 'sha1')
return cert_request
if __name__ == "__main__":
csr = CSR()
cert_name = X509.X509_Name()
keyp = Keypair()
keyp.create_keypair()
keyp.save_keypair("host.key")
pubkey = keyp.get_keypair()
cert_name.C = "GB"
cert_name.ST = "Greater Manchester"
cert_name.L = "Salford"
cert_name.O = "COMODO CA Limited"
cert_name.CN = "COMODO Certification Authority"
cert_name.OU = "Information Technology"
cert_name.Email = "[email protected]"
csr.create_cert_signing_request(pubkey, cert_name)
from M2Crypto import X509, m2, RSA, EVP
from config import *
class Keypair(object):
def __init__(self):
self.config = Config()
self.keypair = EVP.PKey()
def create_keypair(self):
# generate an RSA key pair
# OpenSSL book page 232
# second argument should be a constant RSA_F4 or RSA_3
rsa_key_pair = RSA.gen_key(int(self.config.get_attribute('CA','key_size')), m2.RSA_F4)
# check if RSA key pair is usable
# OpenSSL book page 232
if rsa_key_pair.check_key() != 1:
print 'error while generating key!'
sys.exit()
# EVP object which can hold either a DSA or an RSA object
# OpenSSL book page 236
evp_key_container = EVP.PKey()
evp_key_container.assign_rsa(rsa_key_pair)
self.keypair = evp_key_container
def save_keypair(self, filename):
self.keypair.save_key(filename, None)
def load_keypair(self, filename):
self.keypair = EVP.load_key(filename)
def get_keypair(self):
return self.keypair
def get_public_key(self):
return self.keypair.pkey
def print_keypair(self):
print self.keypair.as_pem(None)
if __name__ == "__main__":
key = Keypair()
key.create_keypair()
key.save_keypair("test.key")
print key.get_keypair()
print key.get_public_key()
Why am I getting this TypeError?
A:
If I change "cert_request.set_pubkey(EVP.PKey(keypair))" to "cert_request.set_pubkey(keypair)" I receive the following Traceback instead. This confuses me even more...
Traceback (most recent call last):
File "csr.py", line 48, in <module>
csr.create_cert_signing_request(pubkey, cert_name)
File "csr.py", line 17, in create_cert_signing_request
cert_request.set_pubkey(keypair)
File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey
return m2.x509_req_set_pubkey( self.req, pkey.pkey )
AttributeError: 'CSR' object has no attribute 'pkey'
|
m2crypto throws "TypeError: in method 'x509_req_set_pubkey'"
|
My little code snippet throws the following Traceback:
Traceback (most recent call last):
File "csr.py", line 48, in <module>
csr.create_cert_signing_request(pubkey, cert_name)
File "csr.py", line 17, in create_cert_signing_request
cert_request.set_pubkey(EVP.PKey(keypair))
File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey
return m2.x509_req_set_pubkey( self.req, pkey.pkey )
TypeError: in method 'x509_req_set_pubkey', argument 2 of type 'EVP_PKEY *'
Here are my two python modules:
from config import *
from keypair import *
from M2Crypto import X509
class CSR(object):
def __init__(self):
pass
def create_cert_signing_request(keypair, cert_name, cert_extension_stack=None):
# create a certificate signing request object
cert_request = X509.Request()
# set certificate version to 3
cert_request.set_version(3)
# which rsa public key should be used?
cert_request.set_pubkey(EVP.PKey(keypair))
# create an subject for the certificate request
cert_request.set_subject_name(cert_name)
if cert_extension_stack != None:
# add the extensions to the request
cert_request.add_extensions(cert_extension_stack)
# sign the request using the RSA key pair
cert_request.sign(keypair, 'sha1')
return cert_request
if __name__ == "__main__":
csr = CSR()
cert_name = X509.X509_Name()
keyp = Keypair()
keyp.create_keypair()
keyp.save_keypair("host.key")
pubkey = keyp.get_keypair()
cert_name.C = "GB"
cert_name.ST = "Greater Manchester"
cert_name.L = "Salford"
cert_name.O = "COMODO CA Limited"
cert_name.CN = "COMODO Certification Authority"
cert_name.OU = "Information Technology"
cert_name.Email = "[email protected]"
csr.create_cert_signing_request(pubkey, cert_name)
from M2Crypto import X509, m2, RSA, EVP
from config import *
class Keypair(object):
def __init__(self):
self.config = Config()
self.keypair = EVP.PKey()
def create_keypair(self):
# generate an RSA key pair
# OpenSSL book page 232
# second argument should be a constant RSA_F4 or RSA_3
rsa_key_pair = RSA.gen_key(int(self.config.get_attribute('CA','key_size')), m2.RSA_F4)
# check if RSA key pair is usable
# OpenSSL book page 232
if rsa_key_pair.check_key() != 1:
print 'error while generating key!'
sys.exit()
# EVP object which can hold either a DSA or an RSA object
# OpenSSL book page 236
evp_key_container = EVP.PKey()
evp_key_container.assign_rsa(rsa_key_pair)
self.keypair = evp_key_container
def save_keypair(self, filename):
self.keypair.save_key(filename, None)
def load_keypair(self, filename):
self.keypair = EVP.load_key(filename)
def get_keypair(self):
return self.keypair
def get_public_key(self):
return self.keypair.pkey
def print_keypair(self):
print self.keypair.as_pem(None)
if __name__ == "__main__":
key = Keypair()
key.create_keypair()
key.save_keypair("test.key")
print key.get_keypair()
print key.get_public_key()
Why am I getting this TypeError?
|
[
"If I change \"cert_request.set_pubkey(EVP.PKey(keypair))\" to \"cert_request.set_pubkey(keypair)\" I receive the following Traceback instead. This confuses me even more... \nTraceback (most recent call last):\n File \"csr.py\", line 48, in <module>\n csr.create_cert_signing_request(pubkey, cert_name)\n File \"csr.py\", line 17, in create_cert_signing_request\n cert_request.set_pubkey(keypair)\n File \"/usr/lib64/python2.6/site-packages/M2Crypto/X509.py\", line 926, in set_pubkey\n return m2.x509_req_set_pubkey( self.req, pkey.pkey )\nAttributeError: 'CSR' object has no attribute 'pkey'\n\n"
] |
[
0
] |
[] |
[] |
[
"m2crypto",
"python"
] |
stackoverflow_0001211843_m2crypto_python.txt
|
Q:
How to create a property with its name in a string?
Using Python I want to create a property in a class, but having the name of it in a string. Normally you do:
blah = property(get_blah, set_blah, del_blah, "bleh blih")
where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this:
setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih"))
But that doesn't work. The first case blah returns the value of the property, on the second case, it returns a property, that is <property object at 0xbb1aa0>. How should I define it so it works?
A:
As much I would say, the difference is, that in the first version, you change the classes attribute blah to the result of property and in the second you set it at the instance (which is different!).
How about this version:
setattr(MyClass, "blah", property(self.get_blah, self.set_blah,
self.del_blah, "bleh blih"))
you can also do this:
setattr(type(self), "blah", property(self.get_blah, self.set_blah,
self.del_blah, "bleh blih"))
A:
One way is to write into locals():
class X:
for attr in ["a","b","c"]:
def getter(self, name=attr):
return name+"_value"
locals()[attr] = property(getter, None, None, attr)
x = X()
print x.a
print x.b
print x.c
gives
a_value
b_value
c_value
A:
If I understand what you're trying to do, you could accomplish it by overriding the class's getattr and setattr methods.
For example:
class Something(object):
def __getattr__(self, name):
# The name of the property retrieved is a string called name
return "You're getting %s" % name
something = Something()
print something.foo
print something.bar
Will print:
You're getting foo
You're getting bar
This way you can have a generic getter and setter that has the name of the property in a string and does something with it accordingly.
|
How to create a property with its name in a string?
|
Using Python I want to create a property in a class, but having the name of it in a string. Normally you do:
blah = property(get_blah, set_blah, del_blah, "bleh blih")
where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this:
setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih"))
But that doesn't work. The first case blah returns the value of the property, on the second case, it returns a property, that is <property object at 0xbb1aa0>. How should I define it so it works?
|
[
"As much I would say, the difference is, that in the first version, you change the classes attribute blah to the result of property and in the second you set it at the instance (which is different!).\nHow about this version:\nsetattr(MyClass, \"blah\", property(self.get_blah, self.set_blah,\n self.del_blah, \"bleh blih\"))\n\nyou can also do this:\nsetattr(type(self), \"blah\", property(self.get_blah, self.set_blah,\n self.del_blah, \"bleh blih\"))\n\n",
"One way is to write into locals():\nclass X:\n for attr in [\"a\",\"b\",\"c\"]:\n def getter(self, name=attr):\n return name+\"_value\"\n locals()[attr] = property(getter, None, None, attr)\n\nx = X()\nprint x.a\nprint x.b\nprint x.c\n\ngives\na_value\nb_value\nc_value\n\n",
"If I understand what you're trying to do, you could accomplish it by overriding the class's getattr and setattr methods.\nFor example:\nclass Something(object):\n def __getattr__(self, name):\n # The name of the property retrieved is a string called name\n return \"You're getting %s\" % name\n\nsomething = Something()\n\nprint something.foo\nprint something.bar\n\nWill print:\nYou're getting foo\nYou're getting bar\n\nThis way you can have a generic getter and setter that has the name of the property in a string and does something with it accordingly.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"properties",
"python",
"setattr"
] |
stackoverflow_0001212434_properties_python_setattr.txt
|
Q:
How to get information about a function and call it
I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(
A:
Try hasattr
>>> help(hasattr)
Help on built-in function hasattr in module __builtin__:
hasattr(...)
hasattr(object, name) -> bool
Return whether the object has an attribute with the given name.
(This is done by calling getattr(object, name) and catching exceptions.)
For more advanced introspection read about the inspect module.
But first, tell us why you need this. There's a 99% chance that a better way exists...
A:
Python supports duck typing - simply call the method on the instance.
A:
Are you trying to align argument values with a function that has a unknown signature?
How will you match up argument values and parameter variables? Guess?
You'd have to use some kind of name matching.
For example something like this.
someObject.someMethod( thisParam=aValue, thatParam=anotherValue )
Oh. Wait. That's already a first-class part of Python.
But what if the method doesn't exist (for inexplicable reasons).
try:
someObject.someMethod( thisParam=aValue, thatParam=anotherValue )
except AttributeError:
method doesn't exist.
A:
class Test(object):
def say_hello(name,msg = "Hello"):
return name +' '+msg
def foo(obj,method_name):
import inspect
# dir gives info about attributes of an object
if method_name in dir(obj):
attr_info = eval('inspect.getargspec(obj.%s)'%method_name)
# here you can implement logic to call the method
# using attribute information
return 'Done'
else:
return 'Method: %s not found for %s'%(method_name,obj.__str__)
if __name__=='__main__':
o1 = Test()
print(foo(o1,'say_hello'))
print(foo(o1,'say_bye'))
I think inspect module will be of very much help to you.
Main functions used in above code are dir,eval,inspect.getargspec. You can get related help in python docs.
|
How to get information about a function and call it
|
I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(
|
[
"Try hasattr\n>>> help(hasattr)\nHelp on built-in function hasattr in module __builtin__:\n\nhasattr(...)\n hasattr(object, name) -> bool\n\n Return whether the object has an attribute with the given name.\n (This is done by calling getattr(object, name) and catching exceptions.)\n\nFor more advanced introspection read about the inspect module.\nBut first, tell us why you need this. There's a 99% chance that a better way exists...\n",
"Python supports duck typing - simply call the method on the instance.\n",
"Are you trying to align argument values with a function that has a unknown signature?\nHow will you match up argument values and parameter variables? Guess?\nYou'd have to use some kind of name matching.\nFor example something like this.\nsomeObject.someMethod( thisParam=aValue, thatParam=anotherValue )\n\nOh. Wait. That's already a first-class part of Python.\nBut what if the method doesn't exist (for inexplicable reasons).\ntry:\n someObject.someMethod( thisParam=aValue, thatParam=anotherValue )\nexcept AttributeError:\n method doesn't exist.\n\n",
"class Test(object):\n def say_hello(name,msg = \"Hello\"):\n return name +' '+msg\n\ndef foo(obj,method_name):\n import inspect\n # dir gives info about attributes of an object\n if method_name in dir(obj):\n attr_info = eval('inspect.getargspec(obj.%s)'%method_name)\n # here you can implement logic to call the method\n # using attribute information\n return 'Done'\n else:\n return 'Method: %s not found for %s'%(method_name,obj.__str__)\n\nif __name__=='__main__': \n o1 = Test()\n print(foo(o1,'say_hello'))\n print(foo(o1,'say_bye'))\n\nI think inspect module will be of very much help to you. \nMain functions used in above code are dir,eval,inspect.getargspec. You can get related help in python docs.\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001212649_python.txt
|
Q:
Threaded application + IntegrityError
I have python threaded application + Postgres. I am using Django's ORM
to save to Postgres..
I have concurrent save calls. Occasionally 2 threads save with the
same primary key which leads to an issue.
Postgres log:
ERROR: duplicate key value violates unique constraint "store_pkey"
STATEMENT: INSERT INTO "store" ("store_id", "address") VALUES
(E'HAN277', E'101 Ocean Street')
Code:
In the code I see an IntegrityError. I tried different ways to handle
this.
a.
try:
a.save()
except IntegrityError:
pass
This causes InternalError
b. Tried to do transaction roll back.. but not sure.. As far as I
understand you need to distinct save calls to have transactions
sid = transaction.savepoint()
try:
row.save()
except IntegrityError, e:
transaction.savepoint_rollback(sid)
pass
transaction.commit()
The first savepoint fails with
AttributeError: 'NoneType' object has no attribute 'cursor'
a. I read somewhere django is not 100% thread safe. Is it a good
choice in my usecase. I was already using Django for other application
and need an ORM.. So naturally I chose Django
b. How to handle this situation.. Any comments.
Thanks and regards,
Ramya
A:
Just to make sure, you're using strings for primary keys if I understand correctly?
AttributeError: 'NoneType' object has no attribute 'cursor'
This means there's an error in some Python code. Have you tried using another version or revision of Django or searching the Django trac for your bug? It isn't so uncommon to be affected by some bug if you're using version from trunk.
As an alternative you could also try to deploy Django using multiple processes instead of multiple threads if that's an option.
However, you might still want to find out why you're getting duplicate requests as it might uncover some other bug.
|
Threaded application + IntegrityError
|
I have python threaded application + Postgres. I am using Django's ORM
to save to Postgres..
I have concurrent save calls. Occasionally 2 threads save with the
same primary key which leads to an issue.
Postgres log:
ERROR: duplicate key value violates unique constraint "store_pkey"
STATEMENT: INSERT INTO "store" ("store_id", "address") VALUES
(E'HAN277', E'101 Ocean Street')
Code:
In the code I see an IntegrityError. I tried different ways to handle
this.
a.
try:
a.save()
except IntegrityError:
pass
This causes InternalError
b. Tried to do transaction roll back.. but not sure.. As far as I
understand you need to distinct save calls to have transactions
sid = transaction.savepoint()
try:
row.save()
except IntegrityError, e:
transaction.savepoint_rollback(sid)
pass
transaction.commit()
The first savepoint fails with
AttributeError: 'NoneType' object has no attribute 'cursor'
a. I read somewhere django is not 100% thread safe. Is it a good
choice in my usecase. I was already using Django for other application
and need an ORM.. So naturally I chose Django
b. How to handle this situation.. Any comments.
Thanks and regards,
Ramya
|
[
"Just to make sure, you're using strings for primary keys if I understand correctly?\n\nAttributeError: 'NoneType' object has no attribute 'cursor'\n\nThis means there's an error in some Python code. Have you tried using another version or revision of Django or searching the Django trac for your bug? It isn't so uncommon to be affected by some bug if you're using version from trunk.\nAs an alternative you could also try to deploy Django using multiple processes instead of multiple threads if that's an option.\nHowever, you might still want to find out why you're getting duplicate requests as it might uncover some other bug.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"postgresql",
"python",
"thread_safety"
] |
stackoverflow_0001212864_django_postgresql_python_thread_safety.txt
|
Q:
Django transaction.commit_on_success not rolling back transaction
I'm trying to use Django transactions on MySQL with the commit_on_success decorator. According to the documentation, "If the function raises an exception, though, Django will roll back the transaction." However, this doesn't seem to work for me:
>>> @transaction.commit_on_success
... def fails():
... Site.objects.create(name="New Site", ip_address="127.0.0.1")
... raise ValueError("oh noes!")
...
>>> Site.objects.count()
2
>>> fails()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/site-packages/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "<stdin>", line 4, in fails
ValueError: oh noes!
>>> Site.objects.count()
3
>>>
I'm pretty sure that MySQL supports transactions; do I need to use a different table type or something?
A:
From http://docs.djangoproject.com/en/dev/ref/databases/:
"The default engine is MyISAM [1]. The main drawback of MyISAM is that it doesn't currently support transactions or foreign keys. On the plus side, it's currently the only engine that supports full-text indexing and searching.
"The InnoDB engine is fully transactional and supports foreign key references."
A:
Apparently MySQL doesn't support transactions with MyISAM tables, which is the default type of tables. InnoDB tables do support transactions, so I'll recreate the tables and then see whether the transactions work then.
|
Django transaction.commit_on_success not rolling back transaction
|
I'm trying to use Django transactions on MySQL with the commit_on_success decorator. According to the documentation, "If the function raises an exception, though, Django will roll back the transaction." However, this doesn't seem to work for me:
>>> @transaction.commit_on_success
... def fails():
... Site.objects.create(name="New Site", ip_address="127.0.0.1")
... raise ValueError("oh noes!")
...
>>> Site.objects.count()
2
>>> fails()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/site-packages/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "<stdin>", line 4, in fails
ValueError: oh noes!
>>> Site.objects.count()
3
>>>
I'm pretty sure that MySQL supports transactions; do I need to use a different table type or something?
|
[
"From http://docs.djangoproject.com/en/dev/ref/databases/:\n\"The default engine is MyISAM [1]. The main drawback of MyISAM is that it doesn't currently support transactions or foreign keys. On the plus side, it's currently the only engine that supports full-text indexing and searching.\n\"The InnoDB engine is fully transactional and supports foreign key references.\"\n",
"Apparently MySQL doesn't support transactions with MyISAM tables, which is the default type of tables. InnoDB tables do support transactions, so I'll recreate the tables and then see whether the transactions work then.\n"
] |
[
8,
3
] |
[] |
[] |
[
"django",
"mysql",
"python",
"transactions"
] |
stackoverflow_0001214143_django_mysql_python_transactions.txt
|
Q:
Making tabulation look different than just whitespace
How to make tabulation look different than whitespace in vim (highlighted for example).
That would be useful for code in Python.
A:
I use something like this:
set list listchars=tab:»·,trail:·,precedes:…,extends:…,nbsp:‗
Requires Vim7 and I'm not sure how well this is going to show up in a browser, because it uses some funky Unicode characters. It's good to use some oddball characters so that you can distinguish a tab from something you may have typed yourself.
In addition to showing tabs, showing spaces at the end of lines is useful so you know to remove them (they are annoying).
A:
Many others have mentioned the 'listchars' and 'list' options, but just to add another interesting alternative:
if &expandtab == 0
execute 'syn match MixedIndentationError display "^\([\t]*\)\@<=\( \{'.&ts.'}\)\+"'
else
execute 'syn match MixedIndentationError display "^\(\( \{' . &ts . '}\)*\)\@<=\t\+"'
endif
hi link MixedIndentationError Error
This will look at the current setting of 'expandtab' (i.e. whether you've got hard tabs or spaces pretending to be tabs) and will highlight anything that would look like correct indentation but be of the wrong form. These are designed to work by looking at the tab stops, so tabs used for indentation followed by spaces used for simple alignment (not a multiple of 'tabstop') won't be highlighted as erroneous.
Simpler options are available: if you just want to highlight any tabs in the wrong file in bright red (or whatever your Error colour is), you could do:
syn match TabShouldNotBeThereError display "\t"
hi link TabShouldNotBeThereError Error
or if you want spaces at the start of a line to be considered an error, you could do:
syn match SpacesUsedForIndentationError display "^ +"
hi link SpacesUsedForIndentationError Error
Just a few more thoughts to add to the mix... more information here:
:help 'expandtab'
:help 'tabstop'
:help 'listchars'
:help 'list'
:help :exe
:help let-option
:help :hi-link
:help :syn-match
:help :syn-display
A:
Use the list and listchars options, something like this:
:set list
:set listchars=tab:>-
A:
If you do the following:
:set list
then all TAB characters will appear as ^I and all trailing spaces will appear as $.
Using listchars, you can control what characters to use for any whitespace. So,
:set listchars=tab:...
in conjunction with :set list makes TABs visible as ....
A:
Also, when cutting and pasting text around, it's useful to disable the display of tabs and spaces. You can do that with
:set list!
And you enable it again with repeating the command.
A:
glenn jackman asked how to enter the characters (I'm assuming he means characters like "»").
Brian Carper suggests a method using the character's Unicode index number. Since many of these distinctive-looking characters are digraphs [ :help digraphs ], you can also use the CNTL-k shortcut, which is generally easier to remember.
So, for example, you can generate the "»" in Insert mode by typing CNTL-k and the ">" character twice.
|
Making tabulation look different than just whitespace
|
How to make tabulation look different than whitespace in vim (highlighted for example).
That would be useful for code in Python.
|
[
"I use something like this:\nset list listchars=tab:»·,trail:·,precedes:…,extends:…,nbsp:‗\n\nRequires Vim7 and I'm not sure how well this is going to show up in a browser, because it uses some funky Unicode characters. It's good to use some oddball characters so that you can distinguish a tab from something you may have typed yourself.\nIn addition to showing tabs, showing spaces at the end of lines is useful so you know to remove them (they are annoying).\n",
"Many others have mentioned the 'listchars' and 'list' options, but just to add another interesting alternative:\nif &expandtab == 0\n execute 'syn match MixedIndentationError display \"^\\([\\t]*\\)\\@<=\\( \\{'.&ts.'}\\)\\+\"'\nelse\n execute 'syn match MixedIndentationError display \"^\\(\\( \\{' . &ts . '}\\)*\\)\\@<=\\t\\+\"'\nendif\nhi link MixedIndentationError Error\n\nThis will look at the current setting of 'expandtab' (i.e. whether you've got hard tabs or spaces pretending to be tabs) and will highlight anything that would look like correct indentation but be of the wrong form. These are designed to work by looking at the tab stops, so tabs used for indentation followed by spaces used for simple alignment (not a multiple of 'tabstop') won't be highlighted as erroneous.\nSimpler options are available: if you just want to highlight any tabs in the wrong file in bright red (or whatever your Error colour is), you could do:\nsyn match TabShouldNotBeThereError display \"\\t\"\nhi link TabShouldNotBeThereError Error\n\nor if you want spaces at the start of a line to be considered an error, you could do:\nsyn match SpacesUsedForIndentationError display \"^ +\"\nhi link SpacesUsedForIndentationError Error\n\nJust a few more thoughts to add to the mix... more information here:\n:help 'expandtab'\n:help 'tabstop'\n:help 'listchars'\n:help 'list'\n:help :exe\n:help let-option\n:help :hi-link\n:help :syn-match\n:help :syn-display\n\n",
"Use the list and listchars options, something like this:\n:set list\n:set listchars=tab:>-\n\n",
"If you do the following:\n:set list\n\nthen all TAB characters will appear as ^I and all trailing spaces will appear as $.\nUsing listchars, you can control what characters to use for any whitespace. So,\n:set listchars=tab:...\n\nin conjunction with :set list makes TABs visible as ....\n",
"Also, when cutting and pasting text around, it's useful to disable the display of tabs and spaces. You can do that with\n:set list!\n\nAnd you enable it again with repeating the command.\n",
"glenn jackman asked how to enter the characters (I'm assuming he means characters like \"»\").\nBrian Carper suggests a method using the character's Unicode index number. Since many of these distinctive-looking characters are digraphs [ :help digraphs ], you can also use the CNTL-k shortcut, which is generally easier to remember.\nSo, for example, you can generate the \"»\" in Insert mode by typing CNTL-k and the \">\" character twice.\n"
] |
[
16,
7,
5,
3,
2,
2
] |
[] |
[] |
[
"python",
"vim"
] |
stackoverflow_0001192480_python_vim.txt
|
Q:
Basic Python dictionary question
I have a dictionary with one key and two values and I want to set each value to a separate variable.
d= {'key' : ('value1, value2'),
'key2' : ('value3, value4'),
'key3' : ('value5, value6')}
I tried d[key][0] in the hope it would return "value1" but instead it return "v"
Any suggestions?
A:
A better solution is to store your value as a two-tuple:
d = {'key' : ('value1', 'value2')}
That way you don't have to split every time you want to access the values.
A:
Try something like this:
d = {'key' : 'value1, value2'}
list = d['key'].split(', ')
list[0] will be "value1" and list[1] will be "value2".
A:
I would suggest storing lists in your dictionary. It'd make it much easier to reference. For instance,
from collections import defaultdict
my_dict = defaultdict(list)
my_dict["key"].append("value 1")
my_dict["key"].append("value 2")
print my_dict["key"][1]
A:
To obtain the two values and assign them to value1 and value2:
for v in d.itervalues():
value1, value2 = v.split(', ')
As said by zenazn, I wouldn't consider this to be a sensible data structure, using a tuple or a class to store the multiple values would be better.
A:
The way you're storing your values, you'll need something like:
value1, value2 = d['key'].split(', ')
print value1, value2
or to iterate over all values:
for key in d:
v1, v2 = d[k].split(', ')
print v1, v2
But, if you can, you should probably follow zenazn's suggestion of storing your values as tuples, and avoid the need to split every time.
|
Basic Python dictionary question
|
I have a dictionary with one key and two values and I want to set each value to a separate variable.
d= {'key' : ('value1, value2'),
'key2' : ('value3, value4'),
'key3' : ('value5, value6')}
I tried d[key][0] in the hope it would return "value1" but instead it return "v"
Any suggestions?
|
[
"A better solution is to store your value as a two-tuple:\nd = {'key' : ('value1', 'value2')}\n\nThat way you don't have to split every time you want to access the values.\n",
"Try something like this:\nd = {'key' : 'value1, value2'}\n\nlist = d['key'].split(', ')\n\nlist[0] will be \"value1\" and list[1] will be \"value2\".\n",
"I would suggest storing lists in your dictionary. It'd make it much easier to reference. For instance,\nfrom collections import defaultdict\n\nmy_dict = defaultdict(list)\nmy_dict[\"key\"].append(\"value 1\")\nmy_dict[\"key\"].append(\"value 2\")\n\nprint my_dict[\"key\"][1] \n\n",
"To obtain the two values and assign them to value1 and value2:\nfor v in d.itervalues():\n value1, value2 = v.split(', ')\n\nAs said by zenazn, I wouldn't consider this to be a sensible data structure, using a tuple or a class to store the multiple values would be better.\n",
"The way you're storing your values, you'll need something like:\nvalue1, value2 = d['key'].split(', ')\nprint value1, value2\n\nor to iterate over all values:\nfor key in d:\n v1, v2 = d[k].split(', ')\n print v1, v2\n\nBut, if you can, you should probably follow zenazn's suggestion of storing your values as tuples, and avoid the need to split every time.\n"
] |
[
17,
4,
2,
2,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0001214422_dictionary_python.txt
|
Q:
Allowing the " - " character in usernames in the Django Admin interface
In our webapp we needed to allow dashes "-" in our usernames.
I've enabled that for the consumer signup process just fine with this regex
r'^[\w-]+$'
How can I tell the admin app so that I can edit usernames in auth > users to allows the "-" character in usernames? Currently I am unable to edit any usernames with dashes in them as it will return a validation error on the username.
I'd like to try and avoid patching django directly if possible.
I'm fairly new to programming but is this what I would use "subclassing" for?
A:
This should be as simple as overriding the behavior of the User ModelAdmin class. In one of your apps, in admin.py include the following code.
from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class MyUserCreationForm(UserCreationForm):
username = forms.RegexField(
label='Username',
max_length=30,
regex=r'^[\w-]+$',
help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
error_message = 'This value must contain only letters, numbers, hyphens and underscores.')
class MyUserChangeForm(UserChangeForm):
username = forms.RegexField(
label='Username',
max_length=30,
regex=r'^[\w-]+$',
help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
error_message = 'This value must contain only letters, numbers, hyphens and underscores.')
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
Here's a little explanation.
The first class definition (MyUserCreationForm) is a subclass (yes your terminology is correct) of the UserCreationForm. This is the form that appears when you click "Add User" in the Django Admin site. All we are doing here is redefining the username field to use our improved, hyphen-accepting regex, and changing the helptext to reflect this.
The second class definition does the same, except for the UserChangeForm.
The final class definition is a subclass of UserAdmin, which is the ModelAdmin that the User model uses by default. Here we state that we want to use our new custom forms in the ModelAdmin.
Note that for each of these subclasses, we only change what we have to. The rest of the class will be inherited from its parent (UserCreationForm, UserChangeForm and UserAdmin respectively).
Finally, we perform the important step of registering the User model with the admin site. To do that we unregister the default UserAdmin, and then register with our improved MyUserAdmin class.
You'll find that the Django admin site is very easy to customize using these techniques, especially considering the admin site is just a regular Django app.
|
Allowing the " - " character in usernames in the Django Admin interface
|
In our webapp we needed to allow dashes "-" in our usernames.
I've enabled that for the consumer signup process just fine with this regex
r'^[\w-]+$'
How can I tell the admin app so that I can edit usernames in auth > users to allows the "-" character in usernames? Currently I am unable to edit any usernames with dashes in them as it will return a validation error on the username.
I'd like to try and avoid patching django directly if possible.
I'm fairly new to programming but is this what I would use "subclassing" for?
|
[
"This should be as simple as overriding the behavior of the User ModelAdmin class. In one of your apps, in admin.py include the following code.\nfrom django.contrib import admin\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm\n\nclass MyUserCreationForm(UserCreationForm):\n username = forms.RegexField(\n label='Username', \n max_length=30, \n regex=r'^[\\w-]+$',\n help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',\n error_message = 'This value must contain only letters, numbers, hyphens and underscores.')\n\nclass MyUserChangeForm(UserChangeForm):\n username = forms.RegexField(\n label='Username', \n max_length=30, \n regex=r'^[\\w-]+$',\n help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',\n error_message = 'This value must contain only letters, numbers, hyphens and underscores.')\n\nclass MyUserAdmin(UserAdmin):\n form = MyUserChangeForm\n add_form = MyUserCreationForm\n\nadmin.site.unregister(User)\nadmin.site.register(User, MyUserAdmin)\n\nHere's a little explanation. \nThe first class definition (MyUserCreationForm) is a subclass (yes your terminology is correct) of the UserCreationForm. This is the form that appears when you click \"Add User\" in the Django Admin site. All we are doing here is redefining the username field to use our improved, hyphen-accepting regex, and changing the helptext to reflect this.\nThe second class definition does the same, except for the UserChangeForm.\nThe final class definition is a subclass of UserAdmin, which is the ModelAdmin that the User model uses by default. Here we state that we want to use our new custom forms in the ModelAdmin.\nNote that for each of these subclasses, we only change what we have to. The rest of the class will be inherited from its parent (UserCreationForm, UserChangeForm and UserAdmin respectively).\nFinally, we perform the important step of registering the User model with the admin site. To do that we unregister the default UserAdmin, and then register with our improved MyUserAdmin class.\nYou'll find that the Django admin site is very easy to customize using these techniques, especially considering the admin site is just a regular Django app.\n"
] |
[
19
] |
[] |
[] |
[
"django",
"django_admin",
"python"
] |
stackoverflow_0001214453_django_django_admin_python.txt
|
Q:
Changing palette's of 8-bit .png images using python PIL
I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so)
What I have tried (edited):
import Image, ImagePalette
output = StringIO.StringIO()
palette = (.....) #long palette of 768 items
im = Image.open('test_palette.png') #8 bit image
im.putpalette(palette)
im.save(output, format='PNG')
With my testimage the save function takes about 65 millis. My thought: without the decoding and encoding, it can be a lot faster??
A:
If you want to change just the palette, then PIL will just get in your way. Luckily, the PNG file format was designed to be easy to deal with when you only are interested in some of the data chunks. The format of the PLTE chunk is just an array of RGB triples, with a CRC at the end. To change the palette on a file in-place without reading or writing the whole file:
import struct
from zlib import crc32
import os
# PNG file format signature
pngsig = '\x89PNG\r\n\x1a\n'
def swap_palette(filename):
# open in read+write mode
with open(filename, 'r+b') as f:
f.seek(0)
# verify that we have a PNG file
if f.read(len(pngsig)) != pngsig:
raise RuntimeError('not a png file!')
while True:
chunkstr = f.read(8)
if len(chunkstr) != 8:
# end of file
break
# decode the chunk header
length, chtype = struct.unpack('>L4s', chunkstr)
# we only care about palette chunks
if chtype == 'PLTE':
curpos = f.tell()
paldata = f.read(length)
# change the 3rd palette entry to cyan
paldata = paldata[:6] + '\x00\xff\xde' + paldata[9:]
# go back and write the modified palette in-place
f.seek(curpos)
f.write(paldata)
f.write(struct.pack('>L', crc32(chtype+paldata)&0xffffffff))
else:
# skip over non-palette chunks
f.seek(length+4, os.SEEK_CUR)
if __name__ == '__main__':
import shutil
shutil.copyfile('redghost.png', 'blueghost.png')
swap_palette('blueghost.png')
This code copies redghost.png over to blueghost.png and modifies the palette of blueghost.png in-place.
->
A:
im.palette is not callable -- it's an instance of the ImagePalette class, in mode P, otherwise None. im.putpalette(...) is a method, so callable: the argument must be a sequence of 768 integers giving R, G and B value at each index.
A:
Changing palette's without decoding and (re)encoding does not seem possible. The method in the question seems best (for now). If performance is important, encoding to GIF seems a lot faster.
|
Changing palette's of 8-bit .png images using python PIL
|
I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so)
What I have tried (edited):
import Image, ImagePalette
output = StringIO.StringIO()
palette = (.....) #long palette of 768 items
im = Image.open('test_palette.png') #8 bit image
im.putpalette(palette)
im.save(output, format='PNG')
With my testimage the save function takes about 65 millis. My thought: without the decoding and encoding, it can be a lot faster??
|
[
"If you want to change just the palette, then PIL will just get in your way. Luckily, the PNG file format was designed to be easy to deal with when you only are interested in some of the data chunks. The format of the PLTE chunk is just an array of RGB triples, with a CRC at the end. To change the palette on a file in-place without reading or writing the whole file:\nimport struct\nfrom zlib import crc32\nimport os\n\n# PNG file format signature\npngsig = '\\x89PNG\\r\\n\\x1a\\n'\n\ndef swap_palette(filename):\n # open in read+write mode\n with open(filename, 'r+b') as f:\n f.seek(0)\n # verify that we have a PNG file\n if f.read(len(pngsig)) != pngsig:\n raise RuntimeError('not a png file!')\n\n while True:\n chunkstr = f.read(8)\n if len(chunkstr) != 8:\n # end of file\n break\n\n # decode the chunk header\n length, chtype = struct.unpack('>L4s', chunkstr)\n # we only care about palette chunks\n if chtype == 'PLTE':\n curpos = f.tell()\n paldata = f.read(length)\n # change the 3rd palette entry to cyan\n paldata = paldata[:6] + '\\x00\\xff\\xde' + paldata[9:]\n\n # go back and write the modified palette in-place\n f.seek(curpos)\n f.write(paldata)\n f.write(struct.pack('>L', crc32(chtype+paldata)&0xffffffff))\n else:\n # skip over non-palette chunks\n f.seek(length+4, os.SEEK_CUR)\n\nif __name__ == '__main__':\n import shutil\n shutil.copyfile('redghost.png', 'blueghost.png')\n swap_palette('blueghost.png')\n\nThis code copies redghost.png over to blueghost.png and modifies the palette of blueghost.png in-place.\n -> \n",
"im.palette is not callable -- it's an instance of the ImagePalette class, in mode P, otherwise None. im.putpalette(...) is a method, so callable: the argument must be a sequence of 768 integers giving R, G and B value at each index.\n",
"Changing palette's without decoding and (re)encoding does not seem possible. The method in the question seems best (for now). If performance is important, encoding to GIF seems a lot faster.\n"
] |
[
8,
1,
0
] |
[] |
[] |
[
"image_processing",
"python",
"python_imaging_library"
] |
stackoverflow_0001158736_image_processing_python_python_imaging_library.txt
|
Q:
Counting and filtering objects in a database with Django
I'm struggling a little to work out how to follow the relation and count fields of objects.
In my Django site, I have a profile model:
user = models.ForeignKey(User, unique=True)
name = models.CharField(_('name'), null=True, blank=True)
about = models.TextField(_('about'), null=True, blank=True)
location = models.CharField(_('location'), null=True, blank=True)
website = models.URLField(_('website'), null=True, blank=True)
My understanding is that this is using the username as the foreign key.
I would like to be able to count and display the number of completed profiles my users have filled out, and ones that have a specific "element / field"? (name)* filled out. I tried:
Profile.objects.all().count()
That gave me the same number of profiles as users, which I am guessing is because the profile model exists for each user, even if it is blank.
I'm unsure how to count profiles that have one of these fields completed in them, and I am also unsure how to count the number of completed "name" fields that have been completed.
I tried:
Profile.objects.all().name.count()
Django has some good docs on queryset api, but its currently going a little over my head
please excuse my use of incorrect terminology.
A:
You should be able to get them using:
Profile.objects.filter(name__isnull=False)
|
Counting and filtering objects in a database with Django
|
I'm struggling a little to work out how to follow the relation and count fields of objects.
In my Django site, I have a profile model:
user = models.ForeignKey(User, unique=True)
name = models.CharField(_('name'), null=True, blank=True)
about = models.TextField(_('about'), null=True, blank=True)
location = models.CharField(_('location'), null=True, blank=True)
website = models.URLField(_('website'), null=True, blank=True)
My understanding is that this is using the username as the foreign key.
I would like to be able to count and display the number of completed profiles my users have filled out, and ones that have a specific "element / field"? (name)* filled out. I tried:
Profile.objects.all().count()
That gave me the same number of profiles as users, which I am guessing is because the profile model exists for each user, even if it is blank.
I'm unsure how to count profiles that have one of these fields completed in them, and I am also unsure how to count the number of completed "name" fields that have been completed.
I tried:
Profile.objects.all().name.count()
Django has some good docs on queryset api, but its currently going a little over my head
please excuse my use of incorrect terminology.
|
[
"You should be able to get them using:\nProfile.objects.filter(name__isnull=False)\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0001214740_django_django_models_python.txt
|
Q:
Text formatting in different versions of Python
I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another.
In python < 2.6, it's done like this:
n = 3
print "%s * %s = %s" % (n, n, n*n)
whereas in python >= 2.6 the best way to do it is:
n = 3
print "{0} * {0} = {1}".format(n, n*n)
But how about when you want the script to be runned in any python version?
What's better, to write python<2.6 code to assure instant compatibility or use the python>=2.6 code that is going to be the way it's used in the future?
Is there any other option to write code for the actual python versions without loosing compatibility with olders?
Thanks
A:
str.format() was introduced in Python 2.6, but its only become the preferred method of string formatting in Python 3.0.
In Python 2.6 both methods will still work, of course.
It all depends on who the consumers of your code will be. If you expect the majority of your users will not be using Python 3.0, then stick with the old formatting.
However, if there is some must-have feature in Python 3.0 that you require for your project, then its not unreasonable to require your users to use a specific version of the interpreter. Keep in mind though that Python 3.0 breaks some pre 3.0 code.
So in summary, if you're targeting Python 3.0, use str.format(). If you're targeting Pyhon <3.0, use % formatting.
A:
What about the good old tuple or string concatenation?
print n, "*", n, "=", n*n
#or
print str(n) + " * " + str(n) + " = " + str(n*n)
it's not as fancy, but should work in any version.
if it's too verbose, maybe a custom function could help:
def format(fmt, values, sep="%%"):
return "".join(str(j) for i in zip(fmt.split(sep), values) for j in i)
#usage
format("%% * %% = %%", [n, n, n*n])
A:
You should have a look at the string.Template (link for 3.1) way to format a string, the API is stable across all versions >=2.5.
I think that concatenation is the simple way to achieve portability for both old and new Python versions. Obviously it's slow, verbose and less pythonic than alternatives.
|
Text formatting in different versions of Python
|
I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another.
In python < 2.6, it's done like this:
n = 3
print "%s * %s = %s" % (n, n, n*n)
whereas in python >= 2.6 the best way to do it is:
n = 3
print "{0} * {0} = {1}".format(n, n*n)
But how about when you want the script to be runned in any python version?
What's better, to write python<2.6 code to assure instant compatibility or use the python>=2.6 code that is going to be the way it's used in the future?
Is there any other option to write code for the actual python versions without loosing compatibility with olders?
Thanks
|
[
"str.format() was introduced in Python 2.6, but its only become the preferred method of string formatting in Python 3.0.\nIn Python 2.6 both methods will still work, of course. \nIt all depends on who the consumers of your code will be. If you expect the majority of your users will not be using Python 3.0, then stick with the old formatting.\nHowever, if there is some must-have feature in Python 3.0 that you require for your project, then its not unreasonable to require your users to use a specific version of the interpreter. Keep in mind though that Python 3.0 breaks some pre 3.0 code.\nSo in summary, if you're targeting Python 3.0, use str.format(). If you're targeting Pyhon <3.0, use % formatting.\n",
"What about the good old tuple or string concatenation?\nprint n, \"*\", n, \"=\", n*n\n#or\nprint str(n) + \" * \" + str(n) + \" = \" + str(n*n)\n\nit's not as fancy, but should work in any version.\nif it's too verbose, maybe a custom function could help:\ndef format(fmt, values, sep=\"%%\"):\n return \"\".join(str(j) for i in zip(fmt.split(sep), values) for j in i)\n\n#usage\nformat(\"%% * %% = %%\", [n, n, n*n])\n\n",
"You should have a look at the string.Template (link for 3.1) way to format a string, the API is stable across all versions >=2.5.\nI think that concatenation is the simple way to achieve portability for both old and new Python versions. Obviously it's slow, verbose and less pythonic than alternatives.\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"formatting",
"python"
] |
stackoverflow_0001212108_formatting_python.txt
|
Q:
Does clause preventing exposure of PyQt in an application's script API close loophole in license?
I am currently evaluating using PyQt in a commercial application, and I was surprised to learn that the PyQt Commercial License does not permit you to expose any of the PyQt library in the application's script API. From the PyQt site:
The right to distribute the required PyQt modules and QScintilla library with your applications so long as the users of those applications do not themselves have direct access to PyQt. Otherwise those users themselves become developers and require their own copies of the commercial versions of both PyQt and Qt.
Is this because if they were allowed access to PyQt you would effectively have a 'loophole' in the PyQt Commercial License? This clause closes that loophole, I assume. I was wondering if there must be a similar clause in the GPL and related licenses? Otherwise, surely, you would be able to release an application under an open-source license that was essentially nothing more than a 'shell' application which allowed people to 'script' its behaviour - said behaviour being the creation of a second, non-GPL application using the GPL PyQt bindings.
I have no doubt that this 'loophole' is addressed in the GPL, which must have had many talented lawyers examining it with fine-toothed combs. - Really, I'm trying to learn more about how law affects the life of a coder. The GPL and other open-source licenses seem a good place to start.
Furthermore, would the same system released under the LGPL have a similar problem? Or does that license's more permissive nature mean that there wouldn't be as much of a conflict allowing users access to the library via an application?
A:
"commercial software" means a software you can sell, including a free GPL'd software. The way the pyqt guys use "commercial" is misleading.
You can use the library under the GPL and charge for it, as long as you provide the code of the program under a GPL compatible license. I don't know what they have that clause -or even a non-free optional license at all-, but it has nothing to do with the GPL. What the pyqt guys are doing is the exact opposite of the GPL: forbidding you to do what you want with the code you paid.
Note that the GPL is not an "Open Source" license but a "Free Software" one. They are two very different groups of people with different ideas. You can read about that at http://www.gnu.org/philosophy/free-software-for-freedom.html#relationship
A:
Will,
If you are coding a Qt application with Python scripting capabilities then you can:
1) Allow the use of Qt on the script via PyQt. This requires a PyQt license per user. Maybe you can offer it as an extra and move the cost to the user that requires it.
2) Expose (using sip or swig) parts of your application that are not PyQt related
3) Create your own interface for Qt (or, at least, the part that you are exposing).
4) Wait for a LGPL version. Unfortunately the current situation is "not for now":
http://www.riverbankcomputing.com/pipermail/pyqt/2009-May/022931.html
|
Does clause preventing exposure of PyQt in an application's script API close loophole in license?
|
I am currently evaluating using PyQt in a commercial application, and I was surprised to learn that the PyQt Commercial License does not permit you to expose any of the PyQt library in the application's script API. From the PyQt site:
The right to distribute the required PyQt modules and QScintilla library with your applications so long as the users of those applications do not themselves have direct access to PyQt. Otherwise those users themselves become developers and require their own copies of the commercial versions of both PyQt and Qt.
Is this because if they were allowed access to PyQt you would effectively have a 'loophole' in the PyQt Commercial License? This clause closes that loophole, I assume. I was wondering if there must be a similar clause in the GPL and related licenses? Otherwise, surely, you would be able to release an application under an open-source license that was essentially nothing more than a 'shell' application which allowed people to 'script' its behaviour - said behaviour being the creation of a second, non-GPL application using the GPL PyQt bindings.
I have no doubt that this 'loophole' is addressed in the GPL, which must have had many talented lawyers examining it with fine-toothed combs. - Really, I'm trying to learn more about how law affects the life of a coder. The GPL and other open-source licenses seem a good place to start.
Furthermore, would the same system released under the LGPL have a similar problem? Or does that license's more permissive nature mean that there wouldn't be as much of a conflict allowing users access to the library via an application?
|
[
"\"commercial software\" means a software you can sell, including a free GPL'd software. The way the pyqt guys use \"commercial\" is misleading.\nYou can use the library under the GPL and charge for it, as long as you provide the code of the program under a GPL compatible license. I don't know what they have that clause -or even a non-free optional license at all-, but it has nothing to do with the GPL. What the pyqt guys are doing is the exact opposite of the GPL: forbidding you to do what you want with the code you paid.\nNote that the GPL is not an \"Open Source\" license but a \"Free Software\" one. They are two very different groups of people with different ideas. You can read about that at http://www.gnu.org/philosophy/free-software-for-freedom.html#relationship\n",
"Will,\nIf you are coding a Qt application with Python scripting capabilities then you can:\n1) Allow the use of Qt on the script via PyQt. This requires a PyQt license per user. Maybe you can offer it as an extra and move the cost to the user that requires it.\n2) Expose (using sip or swig) parts of your application that are not PyQt related\n3) Create your own interface for Qt (or, at least, the part that you are exposing).\n4) Wait for a LGPL version. Unfortunately the current situation is \"not for now\": \nhttp://www.riverbankcomputing.com/pipermail/pyqt/2009-May/022931.html \n"
] |
[
0,
0
] |
[
"First of all: Lawyers rule the world and never you forget it.\nSecondly, IANAL.\nGPL does just the same thing: If you write some code and publish it under the GPL, all derived work must be GPL, too. This is known as the \"viral nature\" of the GPL. R. Stallman specifically added this to protect the work of the GPL developers. You can sell GPL code but you must always include the source. You can change it and sell the result but again, you must include source both of the original code and your modifications.\nIn PyQt's case, this is exactly the same: I could create a small app which just calls QApplication._exec() and leave the \"scripting\" to a \"user\", thus paying only for a single license.\n"
] |
[
-1
] |
[
"gpl",
"licensing",
"open_source",
"pyqt",
"python"
] |
stackoverflow_0001152777_gpl_licensing_open_source_pyqt_python.txt
|
Q:
Looking for a pure Python library for the SyncML protocol
I'm looking for an open source, pure Python library that supports the SyncML protocol, at least enough to implement a SyncML client.
A:
There's https://sourceforge.net/projects/pysyncml/: "The pysyncml library is a pure-python implementation of the SyncML adapter framework and protocol." Haven't tried it yet.
A:
I don't know of any pure Python implementations, but there are python bindings for C libraries:
pysyncml (google for it, can only post 1 link) and
a ctypes-based wrapper that's used by the conduit project.
A:
I can across an implementation of syncml used by the ERP5 project
It is used to sync with mobile devices
link text
|
Looking for a pure Python library for the SyncML protocol
|
I'm looking for an open source, pure Python library that supports the SyncML protocol, at least enough to implement a SyncML client.
|
[
"There's https://sourceforge.net/projects/pysyncml/: \"The pysyncml library is a pure-python implementation of the SyncML adapter framework and protocol.\" Haven't tried it yet.\n",
"I don't know of any pure Python implementations, but there are python bindings for C libraries:\n\npysyncml (google for it, can only post 1 link) and\na ctypes-based wrapper that's used by the conduit project.\n\n",
"I can across an implementation of syncml used by the ERP5 project\nIt is used to sync with mobile devices\nlink text\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python",
"syncml"
] |
stackoverflow_0000831162_python_syncml.txt
|
Q:
XSLT Transform of Unicode source
In my application I am using the 4Suite.org XSLT library to perform transformations of source XML. The syntax is like this:
from Ft.Xml.Xslt import Transform
transformed_xml = Transform(raw_xml, stylesheet)
where raw_xml and stylesheet have been defined elsewhere in my application. raw_xml will be the xml resulting from reading a filehandle opened with the codecs module so the raw_xml will be unicode.
The problem is that the Transform() function requires the value of the source xml (raw_xml in my example) to be ascii. It says so in the pydoc and my own program fails with an error along those lines if I try to transform unicode.
Is there a different approach or is there another python library which can perform an XSLT transformation against a unicode source? Or, am I misunderstanding something about XSLT transformations?
A:
You are likely better off using the more modern and actively maintained lxml.
A:
I'm not sure Transform actually needs ascii -- looks to me like it should support any encoded Python str. What happens if you call Transform(raw_xml.encode('utf8'), stylesheet) (and then decode the resulting utf8-encoded string back to Unicode when you're done processing it of course, if you need Unicode) -- doesn't that work?
|
XSLT Transform of Unicode source
|
In my application I am using the 4Suite.org XSLT library to perform transformations of source XML. The syntax is like this:
from Ft.Xml.Xslt import Transform
transformed_xml = Transform(raw_xml, stylesheet)
where raw_xml and stylesheet have been defined elsewhere in my application. raw_xml will be the xml resulting from reading a filehandle opened with the codecs module so the raw_xml will be unicode.
The problem is that the Transform() function requires the value of the source xml (raw_xml in my example) to be ascii. It says so in the pydoc and my own program fails with an error along those lines if I try to transform unicode.
Is there a different approach or is there another python library which can perform an XSLT transformation against a unicode source? Or, am I misunderstanding something about XSLT transformations?
|
[
"You are likely better off using the more modern and actively maintained lxml.\n",
"I'm not sure Transform actually needs ascii -- looks to me like it should support any encoded Python str. What happens if you call Transform(raw_xml.encode('utf8'), stylesheet) (and then decode the resulting utf8-encoded string back to Unicode when you're done processing it of course, if you need Unicode) -- doesn't that work?\n"
] |
[
2,
2
] |
[] |
[] |
[
"python",
"unicode",
"xslt"
] |
stackoverflow_0001214733_python_unicode_xslt.txt
|
Q:
How to get lxml working under IronPython?
I need to port some code that relies heavily on lxml from a CPython application to IronPython.
lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions.
Does anyone know of a workaround to allow lxml under IronPython or a version of lxml that doesn't have those C-extension dependencies?
A:
You might check out IronClad, which is an open source project intended to make C Extensions for Python available in IronPython.
A:
Something which you might have already considered:
An alternative is to first port the lxml library to IPy and then your code (depending on the code size). You might have to write some C# wrappers for the native C calls to the C extensions -- I'm not sure what issues, if any, are involved in this with regards to IPy.
Or if the code which you are porting is small, as compared to lxml, then maybe you can just remove the lxml dependency and use the .NET XML libraries.
|
How to get lxml working under IronPython?
|
I need to port some code that relies heavily on lxml from a CPython application to IronPython.
lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions.
Does anyone know of a workaround to allow lxml under IronPython or a version of lxml that doesn't have those C-extension dependencies?
|
[
"You might check out IronClad, which is an open source project intended to make C Extensions for Python available in IronPython.\n",
"Something which you might have already considered: \nAn alternative is to first port the lxml library to IPy and then your code (depending on the code size). You might have to write some C# wrappers for the native C calls to the C extensions -- I'm not sure what issues, if any, are involved in this with regards to IPy.\nOr if the code which you are porting is small, as compared to lxml, then maybe you can just remove the lxml dependency and use the .NET XML libraries.\n"
] |
[
2,
1
] |
[] |
[] |
[
".net",
"ironpython",
"lxml",
"python",
"xml"
] |
stackoverflow_0001200726_.net_ironpython_lxml_python_xml.txt
|
Q:
Can a Python function take a generator and return generators to subsets of its generated output?
Let's say I have a generator function like this:
import random
def big_gen():
i = 0
group = 'a'
while group != 'd':
i += 1
yield (group, i)
if random.random() < 0.20:
group = chr(ord(group) + 1)
Example output might be:
('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('a', 6), ('a', 7), ('a', 8), ('b', 9), ('c', 10), ('c', 11), ('c', 12), ('c', 13)
I would like to break this into three groups: Group A, Group B, and Group C. And I would like a generator for each group. Then I'd pass the generator and the group letter into a subfunction. An example of the subfunction:
def printer(group_letter, generator):
print "These numbers are in group %s:" % group_letter
for num in generator:
print "\t%s" % num
The desired output would be:
These numbers are in group a:
1
2
3
4
5
6
7
8
These numbers are in group b:
9
These numbers are in group c:
10
11
12
13
How can I do this without changing big_gen() or printer(), and avoid storing the entire group in memory at once? (In real life, the groups are huge)
A:
Sure, this does what you want:
import itertools
import operator
def main():
for let, gen in itertools.groupby(big_gen(), key=operator.itemgetter(0)):
secgen = itertools.imap(operator.itemgetter(1), gen)
printer(let, secgen)
groupby does the bulk of the work here -- the key= just tells it what field to group by.
The resulting generator needs to be wrapped in an imap just because you've specified your printer signature to take an iterator over number, while, by nature, groupby returns iterators over the same items it gets as its input -- here, 2-items tuples with a letter followed by a number -- but this is not really all that germane to your question's title.
The answer to that title is that, yep, a Python function can perfectly well do the job you want -- itertools.groupby in fact does exactly that. I recommend studying the itertools module carefully, it's a very useful tool (and delivers splendid performance as well).
A:
You have a slight problem here. You'd like the function to printer() to take a generator for each group, but in reality you have the same generator yielding all groups. You have two options, as I see it:
1) Change big_gen() to yield generators:
import random
def big_gen():
i = 0
group = 'a'
while group != 'd':
def gen():
i += 1
yield i
if random.random() < 0.20:
group = chr(ord(group) + 1)
yield group, gen
from itertools import imap
imap(lambda a: printer(*a), big_gen())
2) Change printer() to keep state and notice when the group changes (keeping your original big_gen() function):
def printer(generator):
group = None
for grp, num in generator:
if grp != group:
print "These numbers are in group %s:" % grp
group = grp
print "\t%s" % num
|
Can a Python function take a generator and return generators to subsets of its generated output?
|
Let's say I have a generator function like this:
import random
def big_gen():
i = 0
group = 'a'
while group != 'd':
i += 1
yield (group, i)
if random.random() < 0.20:
group = chr(ord(group) + 1)
Example output might be:
('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('a', 6), ('a', 7), ('a', 8), ('b', 9), ('c', 10), ('c', 11), ('c', 12), ('c', 13)
I would like to break this into three groups: Group A, Group B, and Group C. And I would like a generator for each group. Then I'd pass the generator and the group letter into a subfunction. An example of the subfunction:
def printer(group_letter, generator):
print "These numbers are in group %s:" % group_letter
for num in generator:
print "\t%s" % num
The desired output would be:
These numbers are in group a:
1
2
3
4
5
6
7
8
These numbers are in group b:
9
These numbers are in group c:
10
11
12
13
How can I do this without changing big_gen() or printer(), and avoid storing the entire group in memory at once? (In real life, the groups are huge)
|
[
"Sure, this does what you want:\nimport itertools\nimport operator\n\ndef main():\n for let, gen in itertools.groupby(big_gen(), key=operator.itemgetter(0)):\n secgen = itertools.imap(operator.itemgetter(1), gen)\n printer(let, secgen)\n\ngroupby does the bulk of the work here -- the key= just tells it what field to group by. \nThe resulting generator needs to be wrapped in an imap just because you've specified your printer signature to take an iterator over number, while, by nature, groupby returns iterators over the same items it gets as its input -- here, 2-items tuples with a letter followed by a number -- but this is not really all that germane to your question's title.\nThe answer to that title is that, yep, a Python function can perfectly well do the job you want -- itertools.groupby in fact does exactly that. I recommend studying the itertools module carefully, it's a very useful tool (and delivers splendid performance as well).\n",
"You have a slight problem here. You'd like the function to printer() to take a generator for each group, but in reality you have the same generator yielding all groups. You have two options, as I see it:\n1) Change big_gen() to yield generators:\nimport random\ndef big_gen():\n i = 0\n group = 'a'\n while group != 'd':\n def gen():\n i += 1\n yield i\n if random.random() < 0.20:\n group = chr(ord(group) + 1)\n yield group, gen\n\n from itertools import imap\n imap(lambda a: printer(*a), big_gen())\n\n2) Change printer() to keep state and notice when the group changes (keeping your original big_gen() function):\ndef printer(generator):\n group = None\n for grp, num in generator:\n if grp != group:\n print \"These numbers are in group %s:\" % grp\n group = grp\n print \"\\t%s\" % num\n\n"
] |
[
8,
0
] |
[] |
[] |
[
"generator",
"python"
] |
stackoverflow_0001215464_generator_python.txt
|
Q:
How to list all class properties
I have class SomeClass with properties. For example id and name:
class SomeClass(object):
def __init__(self):
self.__id = None
self.__name = None
def get_id(self):
return self.__id
def set_id(self, value):
self.__id = value
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = value
id = property(get_id, set_id)
name = property(get_name, set_name)
What is the easiest way to list properties? I need this for serialization.
A:
property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]
A:
import inspect
def isprop(v):
return isinstance(v, property)
propnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]
inspect.getmembers gets inherited members as well (and selects members by a predicate, here we coded isprop because it's not among the many predefined ones in module inspect; you could also use a lambda, of course, if you prefer).
|
How to list all class properties
|
I have class SomeClass with properties. For example id and name:
class SomeClass(object):
def __init__(self):
self.__id = None
self.__name = None
def get_id(self):
return self.__id
def set_id(self, value):
self.__id = value
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = value
id = property(get_id, set_id)
name = property(get_name, set_name)
What is the easiest way to list properties? I need this for serialization.
|
[
"property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]\n\n",
"import inspect\n\ndef isprop(v):\n return isinstance(v, property)\n\npropnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]\n\ninspect.getmembers gets inherited members as well (and selects members by a predicate, here we coded isprop because it's not among the many predefined ones in module inspect; you could also use a lambda, of course, if you prefer).\n"
] |
[
55,
36
] |
[] |
[] |
[
"properties",
"python",
"serialization"
] |
stackoverflow_0001215408_properties_python_serialization.txt
|
Q:
Multiple periodic timers
Is there any standard python module for creating multiple periodic timers.
I want to design a system which supports creating multiple periodic timers of different periodicity running in just one thread. The system should be able to cancel a specific timer at any point of time.
Thanks in advance for any input!
A:
Check out the sched module in Python's standard library -- per se, it doesn't directly support periodic timers, only one-off "events", but the standard trick to turn a one-off event into a periodic timer applies (the callable handling the one-off event just reschedules itself for the next repetition, before moving on to doing real work).
It may be handy to define a "scheduled periodic timer" class to encapsulate the key ideas:
class spt(object):
def __init__(self, scheduler, period):
self._sched = scheduler
self._period = period
self._event = None
def start(self):
self._event = self._sched.enter(0, 0, self._action, ())
def _action(self):
self._event - self._sched.enter(self._period, 0, self._action, ())
self.act()
def act(self):
print "hi there"
def cancel(self):
self._sched.cancel(self._event)
To associate a meaningful action to a scheduled periodic timer, subclass spt and override the act method (a Template Method design pattern). You can of course choose more flexible architectures, such as having __init__ take a callable and arguments as well as a scheduler (an instance of self.scheduler) and a period (as a float in seconds, if you instantiate the scheduler in the standard way with time.time and time.sleep); optionally you might also want to set a priority there (maybe with a default value of 0) rather than using the constant 0 priority I'm using above.
A:
If you have to stick with 1 thread - maintain a list of tasks, along with the frequency they should execute and what function should be called:
import time
def example1():
print 'Example'
class Task(object):
def __init__(self, func, delay, args=()):
self.args = args
self.function = func
self.delay = delay
self.next_run = time.time() + self.delay
def shouldRun(self):
return time.time() >= self.next_run
def run(self):
self.function(*(self.args))
self.next_run += self.delay
# self.next_run = time.time() + self.delay
tasks = [Task(example1, 1)] # Run example1 every second
while True:
for t in tasks:
if t.shouldRun():
t.run()
time.sleep(0.01)
Or you may want to have a look at stackless - which is ideally suited to what you want to do, and makes it possible to do much finer grained task-switching than the above scheduler.
|
Multiple periodic timers
|
Is there any standard python module for creating multiple periodic timers.
I want to design a system which supports creating multiple periodic timers of different periodicity running in just one thread. The system should be able to cancel a specific timer at any point of time.
Thanks in advance for any input!
|
[
"Check out the sched module in Python's standard library -- per se, it doesn't directly support periodic timers, only one-off \"events\", but the standard trick to turn a one-off event into a periodic timer applies (the callable handling the one-off event just reschedules itself for the next repetition, before moving on to doing real work).\nIt may be handy to define a \"scheduled periodic timer\" class to encapsulate the key ideas:\nclass spt(object):\n\n def __init__(self, scheduler, period):\n self._sched = scheduler\n self._period = period\n self._event = None\n\n def start(self):\n self._event = self._sched.enter(0, 0, self._action, ())\n\n def _action(self):\n self._event - self._sched.enter(self._period, 0, self._action, ())\n self.act()\n\n def act(self):\n print \"hi there\"\n\n def cancel(self):\n self._sched.cancel(self._event)\n\nTo associate a meaningful action to a scheduled periodic timer, subclass spt and override the act method (a Template Method design pattern). You can of course choose more flexible architectures, such as having __init__ take a callable and arguments as well as a scheduler (an instance of self.scheduler) and a period (as a float in seconds, if you instantiate the scheduler in the standard way with time.time and time.sleep); optionally you might also want to set a priority there (maybe with a default value of 0) rather than using the constant 0 priority I'm using above.\n",
"If you have to stick with 1 thread - maintain a list of tasks, along with the frequency they should execute and what function should be called:\nimport time\n\ndef example1():\n print 'Example'\n\nclass Task(object):\n def __init__(self, func, delay, args=()):\n self.args = args\n self.function = func\n self.delay = delay\n self.next_run = time.time() + self.delay\n\n def shouldRun(self):\n return time.time() >= self.next_run\n\n def run(self):\n self.function(*(self.args))\n self.next_run += self.delay\n # self.next_run = time.time() + self.delay\n\ntasks = [Task(example1, 1)] # Run example1 every second\nwhile True:\n for t in tasks:\n if t.shouldRun():\n t.run()\n time.sleep(0.01)\n\nOr you may want to have a look at stackless - which is ideally suited to what you want to do, and makes it possible to do much finer grained task-switching than the above scheduler.\n"
] |
[
6,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001214164_python.txt
|
Q:
Search engine woes
I have been trying to make this search engine for a MySQL database. Taking in user input is no problem, database querying is also fine.
One thing I need to figure out is this:
I am a string in the database
How do I match the input "AM", but keep the same case? There are PHP functions like str_ireplace or preg_replace/eregi_replace, but what I need to do is split the string according to every exact match (as separate word, so do not match "lAMb", only "am").
That is so I may highlight the matches. Also I need to figure out how to dynamically shorten a string but keep where matches are in the middle:
... this is part of the string where ...
and do this according to font-size set by user in any browser. I had one which only worked in WebKit, but this is no good. Please answer with something like PHP or Python, I'm not a hard-core C kind of guy.
A:
I suggest you read this
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html
It may help you build a better search engine and probably answer some part of your question
Here is a good example of what you could do :
mysql> SELECT id, body, MATCH (title,body) AGAINST
-> ('Security implications of running MySQL as root'
-> IN NATURAL LANGUAGE MODE) AS score
-> FROM articles WHERE MATCH (title,body) AGAINST
-> ('Security implications of running MySQL as root'
-> IN NATURAL LANGUAGE MODE);
+----+-------------------------------------+-----------------+
| id | body | score |
+----+-------------------------------------+-----------------+
| 4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014 |
| 6 | When configured properly, MySQL ... | 1.3114095926285 |
+----+-------------------------------------+-----------------+
2 rows in set (0.00 sec)
|
Search engine woes
|
I have been trying to make this search engine for a MySQL database. Taking in user input is no problem, database querying is also fine.
One thing I need to figure out is this:
I am a string in the database
How do I match the input "AM", but keep the same case? There are PHP functions like str_ireplace or preg_replace/eregi_replace, but what I need to do is split the string according to every exact match (as separate word, so do not match "lAMb", only "am").
That is so I may highlight the matches. Also I need to figure out how to dynamically shorten a string but keep where matches are in the middle:
... this is part of the string where ...
and do this according to font-size set by user in any browser. I had one which only worked in WebKit, but this is no good. Please answer with something like PHP or Python, I'm not a hard-core C kind of guy.
|
[
"I suggest you read this\nhttp://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html\nIt may help you build a better search engine and probably answer some part of your question\nHere is a good example of what you could do :\nmysql> SELECT id, body, MATCH (title,body) AGAINST\n -> ('Security implications of running MySQL as root'\n -> IN NATURAL LANGUAGE MODE) AS score\n -> FROM articles WHERE MATCH (title,body) AGAINST\n -> ('Security implications of running MySQL as root'\n -> IN NATURAL LANGUAGE MODE);\n\n\n +----+-------------------------------------+-----------------+\n | id | body | score |\n +----+-------------------------------------+-----------------+\n | 4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014 |\n | 6 | When configured properly, MySQL ... | 1.3114095926285 |\n +----+-------------------------------------+-----------------+\n 2 rows in set (0.00 sec)\n\n"
] |
[
4
] |
[] |
[] |
[
"javascript",
"mysql",
"php",
"python",
"search"
] |
stackoverflow_0001215661_javascript_mysql_php_python_search.txt
|
Q:
lxml retrieving odd items with cssselector
In my test document I have a few classes labeled "item", currently I'm using the following to parse everything in the html file with this class with
Selection = html.cssselect(".item")
I'd like it to select all the odd items, like this in javascript using JQuery
Selection = $(".item:odd");
Trying that verbatim I get the following error
lxml.cssselect.ExpressionError: The psuedo-class Symbol(u'odd', 6) is unknown
I know this would be trivial to implement on my own, I was wondering if this is supported by lxml natively.
A:
The "odd" and "even" features are part of a selector named "nth-child()"; take a look at the CSS selector specification for more details:
http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#nth-child-pseudo
Therefore, you should be able to get exactly the behavior you want (and it works for me with CSSSelector here) with:
".item:nth-child(odd)"
|
lxml retrieving odd items with cssselector
|
In my test document I have a few classes labeled "item", currently I'm using the following to parse everything in the html file with this class with
Selection = html.cssselect(".item")
I'd like it to select all the odd items, like this in javascript using JQuery
Selection = $(".item:odd");
Trying that verbatim I get the following error
lxml.cssselect.ExpressionError: The psuedo-class Symbol(u'odd', 6) is unknown
I know this would be trivial to implement on my own, I was wondering if this is supported by lxml natively.
|
[
"The \"odd\" and \"even\" features are part of a selector named \"nth-child()\"; take a look at the CSS selector specification for more details:\nhttp://www.w3.org/TR/2001/CR-css3-selectors-20011113/#nth-child-pseudo\n\nTherefore, you should be able to get exactly the behavior you want (and it works for me with CSSSelector here) with:\n\".item:nth-child(odd)\"\n\n"
] |
[
1
] |
[] |
[] |
[
"css",
"html_parsing",
"lxml",
"python"
] |
stackoverflow_0001162580_css_html_parsing_lxml_python.txt
|
Q:
import serial error occured in Python
I wrote
import serial
There message are occured.
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/site-packages/serial/__init__.py", line 20, in ?
from serialposix import *
File "/usr/lib/python2.4/site-packages/serial/serialposix.py", line 13, in ?
import sys, os, fcntl, termios, struct, select, errno
ImportError: No module named termios
What's wrong?
A:
termios has been in the Python standard library since 2.0 at least (I'm not very familiar with older Python versions), but it's always been a Unix-only module. Your 2.4 should be fine, IF you're running under any Unix flavor -- i.e., anything but Windows, more or less. The problem you're seeing suggests either a faulty Python install, or that you're on a non-Unix platform (and if it's not Windows I'm very curious to learn what it IS).
Edit: OP has clarified that they're on Debian -- which has a long history of removing some crucial pieces from upstream components and hiding them in hard-to-locate packages, a history that has long hurt their Python packaging in particular.
I tried several package search engines but I can't find out where they hid termios for Python in particular (for any version) so all I can suggest are workarounds (unless the debian tag I just added attracts debian experts who can help) as well of course as asking on debian-specific forums (clarifying exactly what versions are in use, of course).
Maybe installing another Python (a REAL Python, not the "cleverly packaged", i.e. mangled into pieces and with pieces missing, Debian travesty) might help -- for example, if both sticking with Python 2.4 and using .deb are important constraints to the OP, PYTHON2.4_2.4.6-1UBUNTU3_I386.DEB (not sure how cleanly it and its dependencies install on the OP's specific Debian version, of course); or else, one might as well go with a more recent and complete Python, see for example here (specifically for Debian Etch, but hopefully it can be adapted for the OP's exact version).
|
import serial error occured in Python
|
I wrote
import serial
There message are occured.
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/site-packages/serial/__init__.py", line 20, in ?
from serialposix import *
File "/usr/lib/python2.4/site-packages/serial/serialposix.py", line 13, in ?
import sys, os, fcntl, termios, struct, select, errno
ImportError: No module named termios
What's wrong?
|
[
"termios has been in the Python standard library since 2.0 at least (I'm not very familiar with older Python versions), but it's always been a Unix-only module. Your 2.4 should be fine, IF you're running under any Unix flavor -- i.e., anything but Windows, more or less. The problem you're seeing suggests either a faulty Python install, or that you're on a non-Unix platform (and if it's not Windows I'm very curious to learn what it IS).\nEdit: OP has clarified that they're on Debian -- which has a long history of removing some crucial pieces from upstream components and hiding them in hard-to-locate packages, a history that has long hurt their Python packaging in particular.\nI tried several package search engines but I can't find out where they hid termios for Python in particular (for any version) so all I can suggest are workarounds (unless the debian tag I just added attracts debian experts who can help) as well of course as asking on debian-specific forums (clarifying exactly what versions are in use, of course).\nMaybe installing another Python (a REAL Python, not the \"cleverly packaged\", i.e. mangled into pieces and with pieces missing, Debian travesty) might help -- for example, if both sticking with Python 2.4 and using .deb are important constraints to the OP, PYTHON2.4_2.4.6-1UBUNTU3_I386.DEB (not sure how cleanly it and its dependencies install on the OP's specific Debian version, of course); or else, one might as well go with a more recent and complete Python, see for example here (specifically for Debian Etch, but hopefully it can be adapted for the OP's exact version).\n"
] |
[
3
] |
[] |
[] |
[
"debian",
"python",
"serial_port"
] |
stackoverflow_0001215889_debian_python_serial_port.txt
|
Q:
comparing two strings with 'is' -- not performing as expected
I'm attempting to compare two strings with is. One string is returned by a function, and the other is just declared in the comparison. is tests for object identity, but according to this page, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work:
def uSplit(ustring):
#return user minus host
return ustring.split('!',1)[0]
user = uSplit('theuser!host')
print type(user)
print user
if user is 'theuser':
print 'ok'
else:
print 'failed'
user = 'theuser'
if user is 'theuser':
print 'ok'
The output:
type 'str'
theuser
failed
ok
I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use ==, but I'm just curious.
A:
That page you quoted says "If two string literals are equal, they have been put to same memory location" (emphasis mine). Python interns literal strings, but strings that are returned from some arbitrary function are separate objects. The is operator can be thought of as a pointer comparison, so two different objects will not compare as identical (even if they contain the same characters, ie. they are equal).
A:
The site you quote says this:
If two string literals are equal, they have been put to same memory location.
But
uSplit('theuser!host')
is not a string literal -- it's the result of an operation on the literal 'theuser!host'.
Anyway, you usually shouldn't check for string equality using is, because this memory optimization in any case is just an implementation detail you shouldn't rely on.
Also, You should use is for things like is None. Use it for checking to see if two objects -- of classes that you designed -- are the same instance. You can't easily use it for strings or numbers because the rules for creation of those built-in classes are complex. Some strings are interned. Some numbers, similarly, are interned.
A:
What you have run into is the fact that Python does not always intern all of its strings. More detail here:
http://mail.python.org/pipermail/tutor/2009-July/070157.html
|
comparing two strings with 'is' -- not performing as expected
|
I'm attempting to compare two strings with is. One string is returned by a function, and the other is just declared in the comparison. is tests for object identity, but according to this page, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work:
def uSplit(ustring):
#return user minus host
return ustring.split('!',1)[0]
user = uSplit('theuser!host')
print type(user)
print user
if user is 'theuser':
print 'ok'
else:
print 'failed'
user = 'theuser'
if user is 'theuser':
print 'ok'
The output:
type 'str'
theuser
failed
ok
I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use ==, but I'm just curious.
|
[
"That page you quoted says \"If two string literals are equal, they have been put to same memory location\" (emphasis mine). Python interns literal strings, but strings that are returned from some arbitrary function are separate objects. The is operator can be thought of as a pointer comparison, so two different objects will not compare as identical (even if they contain the same characters, ie. they are equal).\n",
"The site you quote says this:\n\nIf two string literals are equal, they have been put to same memory location.\n\nBut\nuSplit('theuser!host')\n\nis not a string literal -- it's the result of an operation on the literal 'theuser!host'.\nAnyway, you usually shouldn't check for string equality using is, because this memory optimization in any case is just an implementation detail you shouldn't rely on.\n\nAlso, You should use is for things like is None. Use it for checking to see if two objects -- of classes that you designed -- are the same instance. You can't easily use it for strings or numbers because the rules for creation of those built-in classes are complex. Some strings are interned. Some numbers, similarly, are interned.\n",
"What you have run into is the fact that Python does not always intern all of its strings. More detail here:\nhttp://mail.python.org/pipermail/tutor/2009-July/070157.html\n"
] |
[
4,
3,
0
] |
[] |
[] |
[
"python",
"string_comparison",
"string_literals"
] |
stackoverflow_0001216259_python_string_comparison_string_literals.txt
|
Q:
Remap keyboard navigation with Jython / Swing
I'm trying to remap several navigation keys:
ENTER: to work like standard TAB behavior (focus to next control)
SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control)
UP / DOWN arrows: previous /next control
etc
I tried with a couple of options but without luck:
from javax.swing import *
from java.awt import *
class JTextFieldX(JTextField):
def __init__(self, *args):
# Thanks, Jack!!
JTextField.__init__(
self,
focusGained=self.onGotFocus,
focusLost=self.onLostFocus,
*args)
def onGotFocus (self, event):
print "onGotFocus "
self.selectionStart = 0
self.selectionEnd = len(self.text)
def onLostFocus (self, event):
print "onLostFocus ", self.name
class Test(JFrame):
def __init__(self):
JFrame.__init__(self,
'JDesktopPane and JInternalFrame Demo',
size=(600, 300),
defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
self.desktop = JDesktopPane()
self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)
frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
panel = JPanel()
self.label = JLabel('Hello from Jython')
panel.add(self.label)
self.textfield1 = JTextFieldX('Type something here', 15)
panel.add(self.textfield1)
self.textfield2 = JTextFieldX('and click Copy', 15)
panel.add(self.textfield2)
panel.add(copyButton)
frame.add(panel)
frame.pack()
self.desktop.add(frame)
# ENTER=SPACE remapping for buttons (works ok, but only for buttons)
# inputMap = UIManager.getDefaults().get("Button.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed SPACE"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released SPACE"));
# # pressedAction = self.noAction
# inputMap.put (KeyStroke.getKeyStroke("pressed ENTER"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released ENTER"), releasedAction)
# # Attemp to remap ENTER=TAB for TextFields (didn't work, no errors)
# inputMap = UIManager.getDefaults().get("TextField.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed TAB"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released TAB"));
# inputMap.put (KeyStroke.getKeyStroke("pressed W"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released W"), releasedAction)
# # Attemp to remap ENTER=TAB for all controls (didn't work, no errors)
# spaceMap = self.textfield1.getInputMap().get(KeyStroke.getKeyStroke(event.KeyEvent.VK_TAB, 0, True));
# self.textfield1.getInputMap().put(KeyStroke.getKeyStroke(event.KeyEvent.VK_ENTER, 0, True),spaceMap);
frame.setSelected(1)
frame.moveToFront()
def noAction (self, event):
print "noAction"
pass
if __name__ == '__main__':
test = Test()
test.setLocation(100, 100)
test.show()
A:
I made a new post for readability.
self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey)
#create textfield2...must be created before can be referenced below.
self.textfield1.setNextFocusableComponent(self.textfield2)
then in your event handler:
def myOnKey(self,event):
print str(event) # see all other info you can get.
key_code = event.keyCode
if key_code == 10:
print "you pressed enter"
# simulate the "tab" just focus next textbox...
gotFocus = event.getComponent()
nextToFocus = gotFocus.nextFocusableComponent
nextToFocus.requestFocus()
Should do it.
A:
Finally used part of Jack's answer (the keyPressed event) but without manually setting setNextFocusableComponent:
keyFocusMgr = KeyboardFocusManager.getCurrentKeyboardFocusManager()
keyFocusMgr.focusNextComponent()
A:
Add keyPressed to the swing competent that you want to listen for the key press on
self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey)
myOnKey can be named anything in that method do something like:
def myOnKey(self,event):
print str(event) # see all other info you can get.
key_code = event.keyCode
if key_code == 10:
print "you pressed enter"
# simulate the "tab" by just focusing the next textbox...
Then you should just be able to play around with the print str(event) command to get all the proper keycodes that you want.
|
Remap keyboard navigation with Jython / Swing
|
I'm trying to remap several navigation keys:
ENTER: to work like standard TAB behavior (focus to next control)
SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control)
UP / DOWN arrows: previous /next control
etc
I tried with a couple of options but without luck:
from javax.swing import *
from java.awt import *
class JTextFieldX(JTextField):
def __init__(self, *args):
# Thanks, Jack!!
JTextField.__init__(
self,
focusGained=self.onGotFocus,
focusLost=self.onLostFocus,
*args)
def onGotFocus (self, event):
print "onGotFocus "
self.selectionStart = 0
self.selectionEnd = len(self.text)
def onLostFocus (self, event):
print "onLostFocus ", self.name
class Test(JFrame):
def __init__(self):
JFrame.__init__(self,
'JDesktopPane and JInternalFrame Demo',
size=(600, 300),
defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
self.desktop = JDesktopPane()
self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)
frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
panel = JPanel()
self.label = JLabel('Hello from Jython')
panel.add(self.label)
self.textfield1 = JTextFieldX('Type something here', 15)
panel.add(self.textfield1)
self.textfield2 = JTextFieldX('and click Copy', 15)
panel.add(self.textfield2)
panel.add(copyButton)
frame.add(panel)
frame.pack()
self.desktop.add(frame)
# ENTER=SPACE remapping for buttons (works ok, but only for buttons)
# inputMap = UIManager.getDefaults().get("Button.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed SPACE"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released SPACE"));
# # pressedAction = self.noAction
# inputMap.put (KeyStroke.getKeyStroke("pressed ENTER"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released ENTER"), releasedAction)
# # Attemp to remap ENTER=TAB for TextFields (didn't work, no errors)
# inputMap = UIManager.getDefaults().get("TextField.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed TAB"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released TAB"));
# inputMap.put (KeyStroke.getKeyStroke("pressed W"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released W"), releasedAction)
# # Attemp to remap ENTER=TAB for all controls (didn't work, no errors)
# spaceMap = self.textfield1.getInputMap().get(KeyStroke.getKeyStroke(event.KeyEvent.VK_TAB, 0, True));
# self.textfield1.getInputMap().put(KeyStroke.getKeyStroke(event.KeyEvent.VK_ENTER, 0, True),spaceMap);
frame.setSelected(1)
frame.moveToFront()
def noAction (self, event):
print "noAction"
pass
if __name__ == '__main__':
test = Test()
test.setLocation(100, 100)
test.show()
|
[
"I made a new post for readability.\nself.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey)\n\n#create textfield2...must be created before can be referenced below.\n\nself.textfield1.setNextFocusableComponent(self.textfield2)\n\nthen in your event handler:\ndef myOnKey(self,event):\n print str(event) # see all other info you can get.\n key_code = event.keyCode\n if key_code == 10:\n print \"you pressed enter\"\n # simulate the \"tab\" just focus next textbox...\n gotFocus = event.getComponent()\n nextToFocus = gotFocus.nextFocusableComponent\n nextToFocus.requestFocus()\n\nShould do it.\n",
"Finally used part of Jack's answer (the keyPressed event) but without manually setting setNextFocusableComponent:\nkeyFocusMgr = KeyboardFocusManager.getCurrentKeyboardFocusManager()\nkeyFocusMgr.focusNextComponent()\n\n",
"Add keyPressed to the swing competent that you want to listen for the key press on\nself.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey)\n\nmyOnKey can be named anything in that method do something like:\ndef myOnKey(self,event):\n print str(event) # see all other info you can get.\n key_code = event.keyCode\n if key_code == 10:\n print \"you pressed enter\"\n # simulate the \"tab\" by just focusing the next textbox...\n\nThen you should just be able to play around with the print str(event) command to get all the proper keycodes that you want.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"jython",
"python",
"swing"
] |
stackoverflow_0001213730_jython_python_swing.txt
|
Q:
google appengine/python: Can I depend on Task queue retry on failure to keep insertions to a minimum?
Say my app has a page on which people can add comments.
Say after each comment is added a taskqueue worker is added.
So if a 100 comments are added a 100 taskqueue insertions are made.
(note: the above is a hypothetical example to illustrate my question)
Say I wanted to ensure that the number of insertions are kept to a
minimum (so I don't run into the 10k insertion limit)
Could I do something as follows.
a) As each comment is added call taskqueue.add(name="stickytask",
url="/blah")
- Since this is a named taskqueue it will not be re-inserted if a
taskqueue of the same name exists.
b) The /blah worker url reads the newly added comments, processes the
first one and
than if more comments exist to be processed returns a status code
other than 200
- This will ensure that the task is retried and at next try will
process the next comment
and so on.
So all 100 comments are processed with 1 or a few taskqueue insertion.
(Note: If there is a lull
in activity where no new comments are added and all comments are
processed than the
next added comment will result in a new taskqueue insertion. )
However from the docs (see snippet below) it notes that "the system
will back off gradually". Does this mean that on each "non 200" Http
status code returned a delay is inserted into the next retry?
From the docs:
If the execution of a particular Task fails (by returning any HTTP
status code other than 200 OK), App Engine will attempt to retry until
it succeeds. The system will back off gradually so as not to flood
your application with too many requests, but it will retry failed
tasks at least once a day at minimum.
A:
There's no reason to fake a failure (and incur backoff &c) -- that's a hacky and fragile arrangement. If you fear that simply scheduling a task per new comment might exceed the task queues' currently strict limits, then "batch up" as-yet-unprocessed comments in the store (and possibly also in memcache, I guess, for a potential speedup, but, that's optional) and don't schedule any task at that time.
Rather, keep a cron job executing (say) every minute, which may deal with some comments or schedule an appropriate number of tasks to deal with pending comments -- as you schedule tasks from just one cron job, it's easy to ensure you're never scheduling over 10,000 per day.
Don't let task queues make you forget that cron is also there: a good architecture for "batch-like" processing will generally use both cron jobs and queued tasks to simplify its overall design.
To maximize the amount of useful work accomplished in a single request (from ether a queued task or a cron one), consider an approach based on monitoring your CPU usage -- when CPU is the factor limiting the work you can perform per request, this can help you get as many small schedulable units of work done in a single request as is prudently feasible. I think this approach is more solid than waiting for an OverQuotaError, catching it and rapidly closing up, as that may have other consequences out of your app's control.
|
google appengine/python: Can I depend on Task queue retry on failure to keep insertions to a minimum?
|
Say my app has a page on which people can add comments.
Say after each comment is added a taskqueue worker is added.
So if a 100 comments are added a 100 taskqueue insertions are made.
(note: the above is a hypothetical example to illustrate my question)
Say I wanted to ensure that the number of insertions are kept to a
minimum (so I don't run into the 10k insertion limit)
Could I do something as follows.
a) As each comment is added call taskqueue.add(name="stickytask",
url="/blah")
- Since this is a named taskqueue it will not be re-inserted if a
taskqueue of the same name exists.
b) The /blah worker url reads the newly added comments, processes the
first one and
than if more comments exist to be processed returns a status code
other than 200
- This will ensure that the task is retried and at next try will
process the next comment
and so on.
So all 100 comments are processed with 1 or a few taskqueue insertion.
(Note: If there is a lull
in activity where no new comments are added and all comments are
processed than the
next added comment will result in a new taskqueue insertion. )
However from the docs (see snippet below) it notes that "the system
will back off gradually". Does this mean that on each "non 200" Http
status code returned a delay is inserted into the next retry?
From the docs:
If the execution of a particular Task fails (by returning any HTTP
status code other than 200 OK), App Engine will attempt to retry until
it succeeds. The system will back off gradually so as not to flood
your application with too many requests, but it will retry failed
tasks at least once a day at minimum.
|
[
"There's no reason to fake a failure (and incur backoff &c) -- that's a hacky and fragile arrangement. If you fear that simply scheduling a task per new comment might exceed the task queues' currently strict limits, then \"batch up\" as-yet-unprocessed comments in the store (and possibly also in memcache, I guess, for a potential speedup, but, that's optional) and don't schedule any task at that time.\nRather, keep a cron job executing (say) every minute, which may deal with some comments or schedule an appropriate number of tasks to deal with pending comments -- as you schedule tasks from just one cron job, it's easy to ensure you're never scheduling over 10,000 per day.\nDon't let task queues make you forget that cron is also there: a good architecture for \"batch-like\" processing will generally use both cron jobs and queued tasks to simplify its overall design.\nTo maximize the amount of useful work accomplished in a single request (from ether a queued task or a cron one), consider an approach based on monitoring your CPU usage -- when CPU is the factor limiting the work you can perform per request, this can help you get as many small schedulable units of work done in a single request as is prudently feasible. I think this approach is more solid than waiting for an OverQuotaError, catching it and rapidly closing up, as that may have other consequences out of your app's control.\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001216947_google_app_engine_python.txt
|
Q:
Newbie to python conventions, is my code on the right track?
I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)
#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
A:
There's probably a more efficient way to do this using lists and pairs instead of separate variables for each bracket's limit and rate. For instance, consider the following:
# List of (upper-limit, rate) pairs for brackets.
brackets = [ (8350, .10), (33950, .15), (82250, .25), (171550, .28), (372950, .33) ]
if __name__ == '__main__':
salary = float(raw_input("Enter your salary\n"))
accounted_for = 0 # Running total of the portion of salary already taxed
taxed = 0 # Running total of tax from portion of salary already examined
for (limit, rate) in brackets:
if salary < limit:
taxed += ( (salary - accounted_for) * rate )
accounted_for = salary
break # We've found the highest tax bracket we need to bother with
else:
taxed += ( (limit - accounted_for) * rate )
accounted_for = limit
# If we went over the max defined tax bracket, use the final rate
if accounted_for < salary:
taxed += ( (salary - accounted_for) * 0.35 )
print taxed
The idea is that we don't want to repeat code we don't have to just because we have multiple items of similar data to work with. Tax brackets all function the same, aside from differing rates and limits, so we want those to act as inputs to a standard computation as opposed to their own individual functions.
A:
Particularly when working with financial values, you should consider using the decimal module to make sure that there are no floating-point errors in your output.
Not a big deal when you're just making a toy to learn a language, but good to know for future reference :)
A:
4 space indenting! Check out this doc, and the import this output for more. Looks pretty good to me though, very easy to read.
A:
You can change lines like this:
if salary >= 0 and salary <= first_bracket:
to this:
if 0 <= salary <= first_bracket:
like you'd do in mathematics. It generally makes the code more readable.
A:
Since those functions are fairly simple you could do something like:
def b1(a):
return a * .10
you could also make one unified taxing function:
def tax_me(salary, rate):
return salary * rate
Seems like Dav has ya fixed up pretty good :)
Have fun with Python, its a great language.
A:
Structuring the income and tax-rate data as a table (list of tuples or tuple of tuples) is a huge improvement. As shown in that example it allows one to approach the rest of the task with a table driven approach (traverse up the table to find the top rate for a given salary, then traverse from that point downward accumulating taxes and accounting for the total salary).
To make all of this my "Pythonic" we'd define the functionality as well as the tax rate table above the if __name__== line. This would implicitly allow us to import our file into any other code and use that functionary.
The part below the if __name__ == line is then a driver which calls the functionality with any input given (or can be used to hold unit tests, so that any module can be called on to test it's own functionality).
So our code could look something like:
#!/usr/bin/env python
tax_table = (
(8350, 0.10),
...
)
def compute(salary):
'''Compute taxes for a given salary'''
result = 0
accounted_for = 0
...
return result
if __name__ == "__main__":
import sys
try:
sal = float(raw_input("Please enter salary: ")
except EnvironmentError, err:
print >> sys.stderr, "Error with your input, aborting"
print >> sys.stderr, "The error was:", err
sys.exit(1)
print compute(sal)
Notice that we've now separated reusable functionality from our usage ... which allows us to re-use the code ... but also facilitates test-driven development and refactoring. We can write non-interactive test suites using our same API (so far just a call to the compute() function) and this will allow us to refactor with confidence (and without touching our usage below --- which is our "application" in this case).
It's not clear that this particular code would benefit from being refactored into one or more classes. Certainly the ability to instantiate a class with a different tax table would be handy. Then the tax rate could be stored elsewhere (read from a file, pulled off a web server, or queried out of a database; Python make all of those almost equally easy).
However, we don't have to go "OO" to add that functionality to our compute() function.
We could add an optional parameter to the compute function such that it would use a different tax rate table if we provide one, or default to the one we've hard-coded into the module. For that we simple change the initial function definition line to: def compute(salary, table=tax_table): ... and we fix up some handling for the upper limit (factoring the 0.35 rate out of the function and into the table, with either "sys.maxint" as our limit or the "None" object).
For such a simple exercise it's not worth much worry. But in general it's best to put significant effort into defining our desired APIs up front. If you can come up with a robust, flexible API then any conforming implementation that meets your initial requirements (correctness and acceptable performance) will allow you to deliver your application.
More importantly you can then re-implement at will. Perhaps a really complex tax table needs to be searched using something like the bisect module because the linear searches take too long to find the top tax rate, or some sorts of income tax credits and deductions or number of dependents need to be passed into the compute() function, etc.
Ideally such changes can be done transparently. None of your existing usage should have to change because you've done a re-implemented the internals of our module. Even when you've added functionality you shouldn't need to worry about your existing usage (optional parameters and "key word" arguments (dictionaries passed after optional arguments) let us do that for functions, and classes can add attributes and methods without disturbing any proper existing usage. (Yes, it's possible for subclassing usage to be broken by some changes; but that should not usually be a problem).
In Python one can write something as a simple Python module, later re-implement it as a package or re-impement it as a compiled C module or as a package containing some C modules ... all without affecting the usage. From the user's perspective the import statement works identically on Python modules, packages, and compiled modules ("shared objects" or DLLs).
Historically this has been a huge advantage to Python in its own development. They've been able to add considerable functionality to existing libraries and only rarely been forced through "deprecate/rename" contortions. Quite a bit of the functionality slated for Python 3.0 was able to be added to Python 2.7 for this reason.
A:
Tools like PyLint can catch a lot of errors and bad practices, including bad naming conventions. PyChecker is nice too.
|
Newbie to python conventions, is my code on the right track?
|
I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)
#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
|
[
"There's probably a more efficient way to do this using lists and pairs instead of separate variables for each bracket's limit and rate. For instance, consider the following:\n# List of (upper-limit, rate) pairs for brackets.\nbrackets = [ (8350, .10), (33950, .15), (82250, .25), (171550, .28), (372950, .33) ]\n\nif __name__ == '__main__':\n\n salary = float(raw_input(\"Enter your salary\\n\"))\n\n accounted_for = 0 # Running total of the portion of salary already taxed\n taxed = 0 # Running total of tax from portion of salary already examined\n\n for (limit, rate) in brackets:\n if salary < limit:\n taxed += ( (salary - accounted_for) * rate )\n accounted_for = salary\n break # We've found the highest tax bracket we need to bother with\n else:\n taxed += ( (limit - accounted_for) * rate )\n accounted_for = limit\n\n # If we went over the max defined tax bracket, use the final rate\n if accounted_for < salary:\n taxed += ( (salary - accounted_for) * 0.35 )\n\n print taxed\n\nThe idea is that we don't want to repeat code we don't have to just because we have multiple items of similar data to work with. Tax brackets all function the same, aside from differing rates and limits, so we want those to act as inputs to a standard computation as opposed to their own individual functions.\n",
"Particularly when working with financial values, you should consider using the decimal module to make sure that there are no floating-point errors in your output.\nNot a big deal when you're just making a toy to learn a language, but good to know for future reference :)\n",
"4 space indenting! Check out this doc, and the import this output for more. Looks pretty good to me though, very easy to read. \n",
"You can change lines like this:\nif salary >= 0 and salary <= first_bracket:\n\nto this:\nif 0 <= salary <= first_bracket:\n\nlike you'd do in mathematics. It generally makes the code more readable.\n",
"Since those functions are fairly simple you could do something like:\ndef b1(a):\n return a * .10\n\nyou could also make one unified taxing function:\ndef tax_me(salary, rate):\n return salary * rate\n\nSeems like Dav has ya fixed up pretty good :)\nHave fun with Python, its a great language.\n",
"Structuring the income and tax-rate data as a table (list of tuples or tuple of tuples) is a huge improvement. As shown in that example it allows one to approach the rest of the task with a table driven approach (traverse up the table to find the top rate for a given salary, then traverse from that point downward accumulating taxes and accounting for the total salary).\nTo make all of this my \"Pythonic\" we'd define the functionality as well as the tax rate table above the if __name__== line. This would implicitly allow us to import our file into any other code and use that functionary.\nThe part below the if __name__ == line is then a driver which calls the functionality with any input given (or can be used to hold unit tests, so that any module can be called on to test it's own functionality).\nSo our code could look something like:\n#!/usr/bin/env python\ntax_table = (\n(8350, 0.10),\n...\n)\n\ndef compute(salary):\n'''Compute taxes for a given salary'''\nresult = 0\naccounted_for = 0\n...\nreturn result\n\nif __name__ == \"__main__\":\nimport sys\ntry:\nsal = float(raw_input(\"Please enter salary: \")\nexcept EnvironmentError, err:\nprint >> sys.stderr, \"Error with your input, aborting\"\nprint >> sys.stderr, \"The error was:\", err\nsys.exit(1)\nprint compute(sal)\n\nNotice that we've now separated reusable functionality from our usage ... which allows us to re-use the code ... but also facilitates test-driven development and refactoring. We can write non-interactive test suites using our same API (so far just a call to the compute() function) and this will allow us to refactor with confidence (and without touching our usage below --- which is our \"application\" in this case).\nIt's not clear that this particular code would benefit from being refactored into one or more classes. Certainly the ability to instantiate a class with a different tax table would be handy. Then the tax rate could be stored elsewhere (read from a file, pulled off a web server, or queried out of a database; Python make all of those almost equally easy).\nHowever, we don't have to go \"OO\" to add that functionality to our compute() function.\nWe could add an optional parameter to the compute function such that it would use a different tax rate table if we provide one, or default to the one we've hard-coded into the module. For that we simple change the initial function definition line to: def compute(salary, table=tax_table): ... and we fix up some handling for the upper limit (factoring the 0.35 rate out of the function and into the table, with either \"sys.maxint\" as our limit or the \"None\" object).\nFor such a simple exercise it's not worth much worry. But in general it's best to put significant effort into defining our desired APIs up front. If you can come up with a robust, flexible API then any conforming implementation that meets your initial requirements (correctness and acceptable performance) will allow you to deliver your application.\nMore importantly you can then re-implement at will. Perhaps a really complex tax table needs to be searched using something like the bisect module because the linear searches take too long to find the top tax rate, or some sorts of income tax credits and deductions or number of dependents need to be passed into the compute() function, etc.\nIdeally such changes can be done transparently. None of your existing usage should have to change because you've done a re-implemented the internals of our module. Even when you've added functionality you shouldn't need to worry about your existing usage (optional parameters and \"key word\" arguments (dictionaries passed after optional arguments) let us do that for functions, and classes can add attributes and methods without disturbing any proper existing usage. (Yes, it's possible for subclassing usage to be broken by some changes; but that should not usually be a problem).\nIn Python one can write something as a simple Python module, later re-implement it as a package or re-impement it as a compiled C module or as a package containing some C modules ... all without affecting the usage. From the user's perspective the import statement works identically on Python modules, packages, and compiled modules (\"shared objects\" or DLLs).\nHistorically this has been a huge advantage to Python in its own development. They've been able to add considerable functionality to existing libraries and only rarely been forced through \"deprecate/rename\" contortions. Quite a bit of the functionality slated for Python 3.0 was able to be added to Python 2.7 for this reason.\n",
"Tools like PyLint can catch a lot of errors and bad practices, including bad naming conventions. PyChecker is nice too.\n"
] |
[
13,
5,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"conventions",
"python"
] |
stackoverflow_0001216395_conventions_python.txt
|
Q:
is it possible to add an element to a list and preserve the order
I would like to add an element to a list that preserve the order of the list.
Let's assume the list of object is [a, b, c, d] I have a function cmp that compares two elements of the list. if I add f object which is the bigger I would like it to be at the last position.
maybe it's better to sort the complete list...
A:
Yes, this is what bisect.insort is for, however it doesn't take a comparison function. If the objects are custom objects, you can override one or more of the rich comparison methods to establish your desired sort order. Or you could store a 2-tuple with the sort key as the first item, and sort that instead.
A:
bisect.insort is a little bit faster, where applicable, than append-then-sort (unless you have a few elements to add before you need the list to be sorted again) -- measuring as usual on my laptop (a speedier machine will of course be faster across the board, but the ratio should remain roughly constant):
$ python -mtimeit -s'import random, bisect; x=range(20)' 'y=list(x); bisect.insort(y, 22*random.random())'
1000000 loops, best of 3: 1.99 usec per loop
vs
$ python -mtimeit -s'import random, bisect; x=range(20)' 'y=list(x); y.append(22*random.random()); y.sort()'
100000 loops, best of 3: 2.78 usec per loop
How much you care about this difference, of course, depend on how critical a bottleneck this operation is for your application -- there are of course situation where even this fraction of a microsecond makes all the difference, though they are the exception, not the rule.
The bisect module is not as flexible and configurable -- you can easily pass your own custom comparator to sort (although if you can possibly put it in the form of a key= argument you're strongly advised to do that; in Python 3, only key= remains, cmp= is gone, because the performance just couldn't be made good), while bisect rigidly uses built-in comparisons (so you'd have to wrap your objects into wrappers implementing __cmp__ or __le__ to your liking, which also has important performance implications).
In your shoes, I'd start with the append-then-sort approach, and switch to the less-handy bisect approach only if profiling showed that the performance hit was material. Remember Knuth's (and Hoare's) famous quote, and Kent Beck's almost-as-famous one too!-)
A:
L.insert(index, object) -- insert object before index
|
is it possible to add an element to a list and preserve the order
|
I would like to add an element to a list that preserve the order of the list.
Let's assume the list of object is [a, b, c, d] I have a function cmp that compares two elements of the list. if I add f object which is the bigger I would like it to be at the last position.
maybe it's better to sort the complete list...
|
[
"Yes, this is what bisect.insort is for, however it doesn't take a comparison function. If the objects are custom objects, you can override one or more of the rich comparison methods to establish your desired sort order. Or you could store a 2-tuple with the sort key as the first item, and sort that instead.\n",
"bisect.insort is a little bit faster, where applicable, than append-then-sort (unless you have a few elements to add before you need the list to be sorted again) -- measuring as usual on my laptop (a speedier machine will of course be faster across the board, but the ratio should remain roughly constant):\n$ python -mtimeit -s'import random, bisect; x=range(20)' 'y=list(x); bisect.insort(y, 22*random.random())'\n1000000 loops, best of 3: 1.99 usec per loop\n\nvs\n$ python -mtimeit -s'import random, bisect; x=range(20)' 'y=list(x); y.append(22*random.random()); y.sort()'\n100000 loops, best of 3: 2.78 usec per loop\n\nHow much you care about this difference, of course, depend on how critical a bottleneck this operation is for your application -- there are of course situation where even this fraction of a microsecond makes all the difference, though they are the exception, not the rule.\nThe bisect module is not as flexible and configurable -- you can easily pass your own custom comparator to sort (although if you can possibly put it in the form of a key= argument you're strongly advised to do that; in Python 3, only key= remains, cmp= is gone, because the performance just couldn't be made good), while bisect rigidly uses built-in comparisons (so you'd have to wrap your objects into wrappers implementing __cmp__ or __le__ to your liking, which also has important performance implications).\nIn your shoes, I'd start with the append-then-sort approach, and switch to the less-handy bisect approach only if profiling showed that the performance hit was material. Remember Knuth's (and Hoare's) famous quote, and Kent Beck's almost-as-famous one too!-)\n",
"L.insert(index, object) -- insert object before index\n\n"
] |
[
5,
4,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001217780_python.txt
|
Q:
Reverting a Python/Cocoa project to use the default OSX 10.5 Python (2.5)
I have installed the latest MacPython (2.6.2) on my Leopard OS X and started an XCode PyObjC project.
When I finalized the app, I built the release version and sent it to a friend of mine to try if it runs with out of the box. It did not, because it expects the latest Python, as on my computer.
No matter what I tried, I could not find any config file, etc. where I could change this setting to expecting the default Python that came with OS X.
Any and all help will be much appreciated.
Regards,
OA
A:
Uninstalling what you now have in /Library/Frameworks (so XCode falls back to the Python in /System/Library/Frameworks) would work but may be considered a bit drastic. This post and its followups have other potentially useful recommendations, the best one being in the followup at the very end -- you can edit the configurations in /Developer/Library/Xcode/Project Templates/Application/ to determine which Python version XCode projects will be using.
|
Reverting a Python/Cocoa project to use the default OSX 10.5 Python (2.5)
|
I have installed the latest MacPython (2.6.2) on my Leopard OS X and started an XCode PyObjC project.
When I finalized the app, I built the release version and sent it to a friend of mine to try if it runs with out of the box. It did not, because it expects the latest Python, as on my computer.
No matter what I tried, I could not find any config file, etc. where I could change this setting to expecting the default Python that came with OS X.
Any and all help will be much appreciated.
Regards,
OA
|
[
"Uninstalling what you now have in /Library/Frameworks (so XCode falls back to the Python in /System/Library/Frameworks) would work but may be considered a bit drastic. This post and its followups have other potentially useful recommendations, the best one being in the followup at the very end -- you can edit the configurations in /Developer/Library/Xcode/Project Templates/Application/ to determine which Python version XCode projects will be using.\n"
] |
[
1
] |
[] |
[] |
[
"cocoa",
"pyobjc",
"python",
"xcode",
"xcodebuild"
] |
stackoverflow_0001217781_cocoa_pyobjc_python_xcode_xcodebuild.txt
|
Q:
SQLAlchemy: Scan huge tables using ORM?
I am currently playing around with SQLAlchemy a bit, which is really quite neat.
For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast...
For fun I did the equivalent of a select * over the resulting SQLite database:
session = Session()
for p in session.query(Picture):
print(p)
I expected to see hashes scrolling by, but instead it just kept scanning the disk. At the same time, memory usage was skyrocketing, reaching 1GB after a few seconds. This seems to come from the identity map feature of SQLAlchemy, which I thought was only keeping weak references.
Can somebody explain this to me? I thought that each Picture p would be collected after the hash is written out!?
A:
Okay, I just found a way to do this myself. Changing the code to
session = Session()
for p in session.query(Picture).yield_per(5):
print(p)
loads only 5 pictures at a time. It seems like the query will load all rows at a time by default. However, I don't yet understand the disclaimer on that method. Quote from SQLAlchemy docs
WARNING: use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten.
In particular, it’s usually impossible to use this setting with eagerly loaded collections (i.e. any lazy=False) since those collections will be cleared for a new load when encountered in a subsequent result batch.
So if using yield_per is actually the right way (tm) to scan over copious amounts of SQL data while using the ORM, when is it safe to use it?
A:
here's what I usually do for this situation:
def page_query(q):
offset = 0
while True:
r = False
for elem in q.limit(1000).offset(offset):
r = True
yield elem
offset += 1000
if not r:
break
for item in page_query(Session.query(Picture)):
print item
This avoids the various buffering that DBAPIs do as well (such as psycopg2 and MySQLdb). It still needs to be used appropriately if your query has explicit JOINs, although eagerly loaded collections are guaranteed to load fully since they are applied to a subquery which has the actual LIMIT/OFFSET supplied.
I have noticed that Postgresql takes almost as long to return the last 100 rows of a large result set as it does to return the entire result (minus the actual row-fetching overhead) since OFFSET just does a simple scan of the whole thing.
A:
You can defer the picture to only retrieve on access. You can do it on a query by query basis.
like
session = Session()
for p in session.query(Picture).options(sqlalchemy.orm.defer("picture")):
print(p)
or you can do it in the mapper
mapper(Picture, pictures, properties={
'picture': deferred(pictures.c.picture)
})
How you do it is in the documentation here
Doing it either way will make sure that the picture is only loaded when you access the attribute.
|
SQLAlchemy: Scan huge tables using ORM?
|
I am currently playing around with SQLAlchemy a bit, which is really quite neat.
For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast...
For fun I did the equivalent of a select * over the resulting SQLite database:
session = Session()
for p in session.query(Picture):
print(p)
I expected to see hashes scrolling by, but instead it just kept scanning the disk. At the same time, memory usage was skyrocketing, reaching 1GB after a few seconds. This seems to come from the identity map feature of SQLAlchemy, which I thought was only keeping weak references.
Can somebody explain this to me? I thought that each Picture p would be collected after the hash is written out!?
|
[
"Okay, I just found a way to do this myself. Changing the code to\nsession = Session()\nfor p in session.query(Picture).yield_per(5):\n print(p)\n\nloads only 5 pictures at a time. It seems like the query will load all rows at a time by default. However, I don't yet understand the disclaimer on that method. Quote from SQLAlchemy docs\n\nWARNING: use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten.\n In particular, it’s usually impossible to use this setting with eagerly loaded collections (i.e. any lazy=False) since those collections will be cleared for a new load when encountered in a subsequent result batch.\n\nSo if using yield_per is actually the right way (tm) to scan over copious amounts of SQL data while using the ORM, when is it safe to use it?\n",
"here's what I usually do for this situation:\ndef page_query(q):\n offset = 0\n while True:\n r = False\n for elem in q.limit(1000).offset(offset):\n r = True\n yield elem\n offset += 1000\n if not r:\n break\n\nfor item in page_query(Session.query(Picture)):\n print item\n\nThis avoids the various buffering that DBAPIs do as well (such as psycopg2 and MySQLdb). It still needs to be used appropriately if your query has explicit JOINs, although eagerly loaded collections are guaranteed to load fully since they are applied to a subquery which has the actual LIMIT/OFFSET supplied.\nI have noticed that Postgresql takes almost as long to return the last 100 rows of a large result set as it does to return the entire result (minus the actual row-fetching overhead) since OFFSET just does a simple scan of the whole thing.\n",
"You can defer the picture to only retrieve on access. You can do it on a query by query basis.\nlike\nsession = Session()\nfor p in session.query(Picture).options(sqlalchemy.orm.defer(\"picture\")):\n print(p)\n\nor you can do it in the mapper \nmapper(Picture, pictures, properties={\n 'picture': deferred(pictures.c.picture)\n})\n\nHow you do it is in the documentation here\nDoing it either way will make sure that the picture is only loaded when you access the attribute.\n"
] |
[
61,
37,
9
] |
[] |
[] |
[
"orm",
"performance",
"python",
"sqlalchemy"
] |
stackoverflow_0001145905_orm_performance_python_sqlalchemy.txt
|
Q:
Is LINQ (or linq) a niche tool, or is it on the path to becoming foundational?
After reading "What is the Java equivalent of LINQ?", I'd like to know, is (lowercase) language-integrated query - in other words the ability to use a concise syntax for performing queries over object collections or external stores - going to be the path of the future for most general purpose languages? Or is LINQ an interesting piece of technology that will remain confined to Microsoft languages? Something in between?
EDIT: I don't know other languages, but as I am learning it seems like LINQ is neither unprecedented nor unique. The ideas in LINQ - lambdas and queries - are present in other languages, and the ideas seem to be spreading.
A:
Before LinQ, Python had Generator Expressions which are specific syntax for performing queries over collections. Python's syntax is more reduced than Linq's, but let you basically perform the same queries as easy as in linq. Months ago, I wrote a blog post comparing queries in C# and Python, here is a small example:
C# Linq:
var orders = from c in customers
where c.Region == "WA"
from o in c.Orders
where o.OrderDate >= cutoffDate
select new {c.CustomerID, o.OrderID};
Python Generator Expressions:
orders = ( (c.customer_id, o.order_id)
for c in customers if c.region == 'WA'
for o in c.orders if o.date >= cutoff_date)
Syntax for queries in programming languages are an extremely useful tool. I believe every language should include something like that.
A:
After spending years
Handcrafting database access(in oh so many languages)
Going throgh the Entity framework
Fetching and storing data through the fashioned ORM of the month
It was about time somone made an easy to access and language integrated way to talk to a database.
LINQ to SQL should have been made years ago. I applaud the team that come up with it - finally a database access framework that makes sense.
It's not perfect, yet, and my main headache at the moment is there's no real support for LINQ2SQL for other common databases, nor are there anything like it for Java.
(LINQ in general is nice too btw, not just LINQ to SQL :-)
A:
I would say that integrated query technology in any language will become foundational in time, especially given the recent rise in interest of Functional programming languages.
LINQ is certainly one of the biggest reasons I personally am sticking with .NET, anyway - it's become foundational for me personally, and I'd wager a lot of devs feel this way as well.
A:
I think the functional concepts which are the under pinnings of LINQ will become popular in many languages. Passing a sequence of objects through a set of functions to get the desired set of objects. Essentially, using the lambda syntax over the query syntax.
This is a very powerful and expressive way of coding.
This is not because I feel it's a fundamentally better way to do things (i.e. lambda over query syntax). Comparatively speaking, it's much easier to add the underlying library support for query expressions to a language than it is to add the query syntax. All that is required the lambda syntax for queries is
Lambdas
Underlying query methods
Most new languages support lambdas (even C++ is finally getting them!). Adding the library support is fairly cheap and can usually be done by a motivated individual.
Getting the query syntax into the language though requires a lot more work.
A:
Disclaimer: I've never used LINQ. Please correct me if I'm wrong.
Many languages have constructs which allow to the same things as LINQ with the language data types.
Apparently the most interesting feature is that LINQ constructs can be converted to SQL, but it's not specific to LINQ: http://www.aminus.org/blogs/index.php/2008/04/22/linq-in-python?blog=2.
A:
I don't think linq will be confined to the microsoft languages, check it out, there is already something for the php, check it out http://phplinq.codeplex.com/
I think Linq is great tool in development process and personally would be really glad if it will be transferred to other languages(like in my example of php)
A:
I don't think that you can really classify it (or many things) as either. While I would hardly say that LINQ is a niche tool -- it has many applications to many people -- it's not "foundational" IMO. However, I also wouldn't say that having LINQ (or an equivalent) language-specific querying language can be truly foundational at this stage of the game. In the future, perhaps, but right now you can construct a query in many different ways that yield SIGNIFICANTLY varying levels of performance.
A:
It sounds a lot to me like Ruby's Active Record, but I've never used LINQ. Anyone used both? (I would have posted this as a comment, but I'd really like to be updated on the answer--I'm probably wrong so it'll get downvoted :) )
(Actually I should say that AR is like LINQ to SQL, they haven't implemented AR for other targets as far as I know)
|
Is LINQ (or linq) a niche tool, or is it on the path to becoming foundational?
|
After reading "What is the Java equivalent of LINQ?", I'd like to know, is (lowercase) language-integrated query - in other words the ability to use a concise syntax for performing queries over object collections or external stores - going to be the path of the future for most general purpose languages? Or is LINQ an interesting piece of technology that will remain confined to Microsoft languages? Something in between?
EDIT: I don't know other languages, but as I am learning it seems like LINQ is neither unprecedented nor unique. The ideas in LINQ - lambdas and queries - are present in other languages, and the ideas seem to be spreading.
|
[
"Before LinQ, Python had Generator Expressions which are specific syntax for performing queries over collections. Python's syntax is more reduced than Linq's, but let you basically perform the same queries as easy as in linq. Months ago, I wrote a blog post comparing queries in C# and Python, here is a small example:\nC# Linq:\nvar orders = from c in customers\n where c.Region == \"WA\"\n from o in c.Orders\n where o.OrderDate >= cutoffDate\n select new {c.CustomerID, o.OrderID};\n\nPython Generator Expressions:\norders = ( (c.customer_id, o.order_id)\n for c in customers if c.region == 'WA'\n for o in c.orders if o.date >= cutoff_date)\n\nSyntax for queries in programming languages are an extremely useful tool. I believe every language should include something like that.\n",
"After spending years\n\nHandcrafting database access(in oh so many languages)\nGoing throgh the Entity framework\nFetching and storing data through the fashioned ORM of the month\n\nIt was about time somone made an easy to access and language integrated way to talk to a database.\nLINQ to SQL should have been made years ago. I applaud the team that come up with it - finally a database access framework that makes sense.\nIt's not perfect, yet, and my main headache at the moment is there's no real support for LINQ2SQL for other common databases, nor are there anything like it for Java.\n(LINQ in general is nice too btw, not just LINQ to SQL :-)\n",
"I would say that integrated query technology in any language will become foundational in time, especially given the recent rise in interest of Functional programming languages.\nLINQ is certainly one of the biggest reasons I personally am sticking with .NET, anyway - it's become foundational for me personally, and I'd wager a lot of devs feel this way as well.\n",
"I think the functional concepts which are the under pinnings of LINQ will become popular in many languages. Passing a sequence of objects through a set of functions to get the desired set of objects. Essentially, using the lambda syntax over the query syntax. \nThis is a very powerful and expressive way of coding. \nThis is not because I feel it's a fundamentally better way to do things (i.e. lambda over query syntax). Comparatively speaking, it's much easier to add the underlying library support for query expressions to a language than it is to add the query syntax. All that is required the lambda syntax for queries is \n\nLambdas\nUnderlying query methods\n\nMost new languages support lambdas (even C++ is finally getting them!). Adding the library support is fairly cheap and can usually be done by a motivated individual. \nGetting the query syntax into the language though requires a lot more work. \n",
"Disclaimer: I've never used LINQ. Please correct me if I'm wrong.\nMany languages have constructs which allow to the same things as LINQ with the language data types.\nApparently the most interesting feature is that LINQ constructs can be converted to SQL, but it's not specific to LINQ: http://www.aminus.org/blogs/index.php/2008/04/22/linq-in-python?blog=2.\n",
"I don't think linq will be confined to the microsoft languages, check it out, there is already something for the php, check it out http://phplinq.codeplex.com/\nI think Linq is great tool in development process and personally would be really glad if it will be transferred to other languages(like in my example of php)\n",
"I don't think that you can really classify it (or many things) as either. While I would hardly say that LINQ is a niche tool -- it has many applications to many people -- it's not \"foundational\" IMO. However, I also wouldn't say that having LINQ (or an equivalent) language-specific querying language can be truly foundational at this stage of the game. In the future, perhaps, but right now you can construct a query in many different ways that yield SIGNIFICANTLY varying levels of performance. \n",
"It sounds a lot to me like Ruby's Active Record, but I've never used LINQ. Anyone used both? (I would have posted this as a comment, but I'd really like to be updated on the answer--I'm probably wrong so it'll get downvoted :) )\n(Actually I should say that AR is like LINQ to SQL, they haven't implemented AR for other targets as far as I know)\n"
] |
[
9,
4,
2,
2,
1,
1,
0,
0
] |
[] |
[] |
[
".net",
"java",
"linq",
"python"
] |
stackoverflow_0001217274_.net_java_linq_python.txt
|
Q:
PyOpenGL + Pygame capped to 60 FPS in Fullscreen
I'm currently working on a game engine written in pygame and I wanted to add OpenGL support.
I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I did was add the FULLSCREEN flag when I set up the window), it drops down to 60 fps. I added a lot more drawing functions to see if it was just a huge performance drop, but it always ran at 60 fps.
Is there something extra I need to do to tell OpenGL that it's running fullscreen or is this a limitation of OpenGL?
(I am running in Windows XP)
A:
As frou pointed out, this would be due to Pygame waiting for the vertical retrace when you update the screen by calling display.flip(). As the Pygame display documentation notes, if you set the display mode using the HWSURFACE or the DOUBLEBUF flags, display.flip() will wait for the vertical retrace before swapping buffers.
To be honest, I don't see any good reason (aside from benchmarking) to try to achieve a frame rate that's faster than the screen's refresh rate. You (and the people playing your game) won't be able to notice any difference in speed or performance, since the display can only draw 60 fps anyways. Plus, if you don't sync with the vertical retrace, there's a good chance that you'll get screen tearing.
A:
Is this a V-Sync issue? Something about the config or your environment may be limiting maximum frame rate to your monitor's refresh rate.
A:
If you are not changing your clock.tick() when you change between full screen and windowed mode this is almost certainly a vsync issue. If you are on an LCD then it's 100% certain.
Unfortunately v-sync can be handled in many places including SDL, Pyopengl, your display server and your video drivers. If you are using windows you can adjust the vsync toggle in the nvidia control panel to test, and there's more than likely something in nvidia-settings for linux as well. I'd guess other manufacturers drivers have similar settings but that's a guess.
|
PyOpenGL + Pygame capped to 60 FPS in Fullscreen
|
I'm currently working on a game engine written in pygame and I wanted to add OpenGL support.
I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I did was add the FULLSCREEN flag when I set up the window), it drops down to 60 fps. I added a lot more drawing functions to see if it was just a huge performance drop, but it always ran at 60 fps.
Is there something extra I need to do to tell OpenGL that it's running fullscreen or is this a limitation of OpenGL?
(I am running in Windows XP)
|
[
"As frou pointed out, this would be due to Pygame waiting for the vertical retrace when you update the screen by calling display.flip(). As the Pygame display documentation notes, if you set the display mode using the HWSURFACE or the DOUBLEBUF flags, display.flip() will wait for the vertical retrace before swapping buffers.\nTo be honest, I don't see any good reason (aside from benchmarking) to try to achieve a frame rate that's faster than the screen's refresh rate. You (and the people playing your game) won't be able to notice any difference in speed or performance, since the display can only draw 60 fps anyways. Plus, if you don't sync with the vertical retrace, there's a good chance that you'll get screen tearing.\n",
"Is this a V-Sync issue? Something about the config or your environment may be limiting maximum frame rate to your monitor's refresh rate.\n",
"If you are not changing your clock.tick() when you change between full screen and windowed mode this is almost certainly a vsync issue. If you are on an LCD then it's 100% certain.\nUnfortunately v-sync can be handled in many places including SDL, Pyopengl, your display server and your video drivers. If you are using windows you can adjust the vsync toggle in the nvidia control panel to test, and there's more than likely something in nvidia-settings for linux as well. I'd guess other manufacturers drivers have similar settings but that's a guess. \n"
] |
[
8,
1,
0
] |
[] |
[] |
[
"fullscreen",
"pygame",
"pyopengl",
"python"
] |
stackoverflow_0001217939_fullscreen_pygame_pyopengl_python.txt
|
Q:
The wrong python interpreter is called
I updated my python interpreter, but I think the old one is still called. When I check for the version I get:
$ python -V
Python 3.0.1
But I believe the old interpreter is still being called. When I run the command:
python myProg.py
The script runs properly. But when I invoke it with the command
./myProg.py
I get the error message:
AttributeError: 'str' object has no attribute 'format'
Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:
#!/usr/bin/python
I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.
A:
According to the first line of the script, #!/usr/bin/python, you are calling the Python interpreter at /usr/bin/python (which is most likely the one that ships with Mac OS X). You have to change that path to the path where you installed your Python 3 interpreter (likely /usr/local/bin/python or /opt/local/bin/python); or you can just change that line to read #!/usr/bin/env python, which will call the python listed first in your PATH variable (which seems to be the newer version you installed).
A:
Firstly, the recommended shebang line is:
#!/usr/bin/env python
This will make sure the python interpreter that is invoked when you ./foo.py is the same interpreter that is invoked when you invoke python from the command line.
From your description, I suspect that if you did:
which python
It would not give you /usr/bin/python. It would give you something else, which is where the python 3 interpreter lives. You can either modify your shebang line to the above, or replace the path to the python interpreter with the path returned by which.
A:
Try which python. I will tell you which python interpreter is used in your environment.
If it is not /usr/bin/python like in the script, then your suspicion is confirmed.
A:
It's very possibly what you suspect, that the shebang line is calling the older version. Two things you might want to check:
1) what version is the interpreter at /usr/bin/python:
/usr/bin/python -V
2) where is the python 3 interpreter you installed:
which python
If you get the correct one from the command line, then replace your shebang line with this:
#!/usr/bin/env python
Addendum: You could also replace the older version of python with a symlink to python 3, but beware that any major OS X updates (ie: 10.5.6 to 10.5.7) will likely break this:
sudo mv /usr/bin/python /usr/bin/python25
sudo ln -s /path/to/python/3/python /usr/bin/python
A:
run 'which python' - if this gives a different answer than /usr/bin/python, change #!/usr/bin/python to have that path instead.
A:
It may be a bit odd providing a Perl script to answer a Python question, but it works for Python just as well as it does for Perl. This is a script called 'fixin', meaning 'fix interpreter'. It changes the shebang line to the correct string for your current PATH.
#!/Users/jleffler/perl/v5.10.0/bin/perl
#
# @(#)$Id: fixin.pl,v 1.3 2003/03/11 21:20:08 jleffler Exp $
#
# FIXIN: from Programming Perl
# Usage: fixin [-s] [file ...]
# Configuration
$does_hashbang = 1; # Kernel recognises #!
$verbose = 1; # Verbose by default
# Construct list of directories to search.
@absdirs = reverse grep(m!^/!, split(/:/, $ENV{'PATH'}, 999));
# Process command line arguments
if ($ARGV[0] eq '-s')
{
shift;
$verbose = 0;
}
die "Usage: $0 [-s] [file ...]\n" unless @ARGV || !-t;
@ARGV = '-' unless @ARGV;
# Process each file.
FILE: foreach $filename (@ARGV)
{
open(IN, $filename) || ((warn "Can't process $filename: $!\n"), next);
$_ = <IN>;
next FILE unless /^#!/; # Not a hash/bang file
chop($cmd = $_);
$cmd =~ s/^#! *//;
($cmd, $arg) = split(' ', $cmd, 2);
$cmd =~ s!^.*/!!;
# Now look (in reverse) for interpreter in absolute path
$found = '';
foreach $dir (@absdirs)
{
if (-x "$dir/$cmd")
{
warn "Ignoring $found\n" if $verbose && $found;
$found = "$dir/$cmd";
}
}
# Figure out how to invoke interpreter on this machine
if ($found)
{
warn "Changing $filename to $found\n" if $verbose;
if ($does_hashbang)
{
$_ = "#!$found";
$_ .= ' ' . $arg if $arg ne '';
$_ .= "\n";
}
else
{
$_ = <<EOF;
:
eval 'exec $found $arg -S \$0 \${1+"\$@"}'
if \$running_under_some_shell;
EOF
}
}
else
{
warn "Can't find $cmd in PATH, $filename unchanged\n" if $verbose;
next FILE;
}
# Make new file if necessary
if ($filename eq '-') { select(STDOUT); }
else
{
rename($filename, "$filename.bak") ||
((warn "Can't modify $filename"), next FILE);
open(OUT, ">$filename") ||
die "Can't create new $filename: $!\n";
($def, $ino, $mode) = stat IN;
$mode = 0755 unless $dev;
chmod $mode, $filename;
select(OUT);
}
# Print the new #! line (or the equivalent) and copy the rest of the file.
print;
while (<IN>)
{
print;
}
close IN;
close OUT;
}
The code is derived from a script of the same name in the original Camel Book ('Programming Perl', first edition). This copy has been hacked a bit since then - and should be hacked some more. But I use it routinely -- indeed, I just copied it from one Mac to another, and since I've not installed Perl 5.10.0 on the second, I ran:
$ perl fixin fixin
Changing fixin to /usr/bin/perl
$
Thereby changing from the private install Perl to the standard one.
Exercise for the reader - rewrite the script in Python.
|
The wrong python interpreter is called
|
I updated my python interpreter, but I think the old one is still called. When I check for the version I get:
$ python -V
Python 3.0.1
But I believe the old interpreter is still being called. When I run the command:
python myProg.py
The script runs properly. But when I invoke it with the command
./myProg.py
I get the error message:
AttributeError: 'str' object has no attribute 'format'
Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:
#!/usr/bin/python
I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.
|
[
"According to the first line of the script, #!/usr/bin/python, you are calling the Python interpreter at /usr/bin/python (which is most likely the one that ships with Mac OS X). You have to change that path to the path where you installed your Python 3 interpreter (likely /usr/local/bin/python or /opt/local/bin/python); or you can just change that line to read #!/usr/bin/env python, which will call the python listed first in your PATH variable (which seems to be the newer version you installed).\n",
"Firstly, the recommended shebang line is:\n#!/usr/bin/env python\n\nThis will make sure the python interpreter that is invoked when you ./foo.py is the same interpreter that is invoked when you invoke python from the command line.\nFrom your description, I suspect that if you did:\nwhich python\n\nIt would not give you /usr/bin/python. It would give you something else, which is where the python 3 interpreter lives. You can either modify your shebang line to the above, or replace the path to the python interpreter with the path returned by which.\n",
"Try which python. I will tell you which python interpreter is used in your environment.\nIf it is not /usr/bin/python like in the script, then your suspicion is confirmed.\n",
"It's very possibly what you suspect, that the shebang line is calling the older version. Two things you might want to check:\n1) what version is the interpreter at /usr/bin/python:\n/usr/bin/python -V\n\n2) where is the python 3 interpreter you installed:\nwhich python\n\nIf you get the correct one from the command line, then replace your shebang line with this:\n#!/usr/bin/env python\n\nAddendum: You could also replace the older version of python with a symlink to python 3, but beware that any major OS X updates (ie: 10.5.6 to 10.5.7) will likely break this:\nsudo mv /usr/bin/python /usr/bin/python25\nsudo ln -s /path/to/python/3/python /usr/bin/python\n\n",
"run 'which python' - if this gives a different answer than /usr/bin/python, change #!/usr/bin/python to have that path instead.\n",
"It may be a bit odd providing a Perl script to answer a Python question, but it works for Python just as well as it does for Perl. This is a script called 'fixin', meaning 'fix interpreter'. It changes the shebang line to the correct string for your current PATH.\n#!/Users/jleffler/perl/v5.10.0/bin/perl\n#\n# @(#)$Id: fixin.pl,v 1.3 2003/03/11 21:20:08 jleffler Exp $\n#\n# FIXIN: from Programming Perl\n# Usage: fixin [-s] [file ...]\n\n# Configuration\n$does_hashbang = 1; # Kernel recognises #!\n$verbose = 1; # Verbose by default\n\n# Construct list of directories to search.\n@absdirs = reverse grep(m!^/!, split(/:/, $ENV{'PATH'}, 999));\n\n# Process command line arguments\nif ($ARGV[0] eq '-s')\n{\n shift;\n $verbose = 0;\n}\ndie \"Usage: $0 [-s] [file ...]\\n\" unless @ARGV || !-t;\n\n@ARGV = '-' unless @ARGV;\n\n# Process each file.\nFILE: foreach $filename (@ARGV)\n{\n open(IN, $filename) || ((warn \"Can't process $filename: $!\\n\"), next);\n $_ = <IN>;\n next FILE unless /^#!/; # Not a hash/bang file\n\n chop($cmd = $_);\n $cmd =~ s/^#! *//;\n ($cmd, $arg) = split(' ', $cmd, 2);\n $cmd =~ s!^.*/!!;\n\n # Now look (in reverse) for interpreter in absolute path\n $found = '';\n foreach $dir (@absdirs)\n {\n if (-x \"$dir/$cmd\")\n {\n warn \"Ignoring $found\\n\" if $verbose && $found;\n $found = \"$dir/$cmd\";\n }\n }\n\n # Figure out how to invoke interpreter on this machine\n if ($found)\n {\n warn \"Changing $filename to $found\\n\" if $verbose;\n if ($does_hashbang)\n {\n $_ = \"#!$found\";\n $_ .= ' ' . $arg if $arg ne '';\n $_ .= \"\\n\";\n }\n else\n {\n $_ = <<EOF;\n:\neval 'exec $found $arg -S \\$0 \\${1+\"\\$@\"}'\n if \\$running_under_some_shell;\nEOF\n }\n }\n else\n {\n warn \"Can't find $cmd in PATH, $filename unchanged\\n\" if $verbose;\n next FILE;\n }\n\n # Make new file if necessary\n if ($filename eq '-') { select(STDOUT); }\n else\n {\n rename($filename, \"$filename.bak\") ||\n ((warn \"Can't modify $filename\"), next FILE);\n open(OUT, \">$filename\") ||\n die \"Can't create new $filename: $!\\n\";\n ($def, $ino, $mode) = stat IN;\n $mode = 0755 unless $dev;\n chmod $mode, $filename;\n select(OUT);\n }\n\n # Print the new #! line (or the equivalent) and copy the rest of the file.\n print;\n while (<IN>)\n {\n print;\n }\n close IN;\n close OUT;\n}\n\nThe code is derived from a script of the same name in the original Camel Book ('Programming Perl', first edition). This copy has been hacked a bit since then - and should be hacked some more. But I use it routinely -- indeed, I just copied it from one Mac to another, and since I've not installed Perl 5.10.0 on the second, I ran:\n$ perl fixin fixin\nChanging fixin to /usr/bin/perl\n$\n\nThereby changing from the private install Perl to the standard one.\nExercise for the reader - rewrite the script in Python.\n"
] |
[
16,
6,
3,
3,
2,
1
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0000904170_python_python_3.x.txt
|
Q:
In erlang: How do I expand wxNotebook in a panel?
(I have tagged this question as Python as well since I understand Python code so examples in Python are also welcome!).
I want to create a simple window in wxWidgets:
I create a main panel which I add to a form
I associate a boxsizer to the main panel (splitting it in two, horizontally).
I add LeftPanel to the boxsizer,
I add RightPanel to the boxsizer,
I create a new boxsizer (vertical)
I create another boxsizer (horizontal)
I create a Notebook widget
I create a Panel and put it inside the Notebook (addpage)
I add the notebook to the new boxsizer (vertical one)
I add the vertical sizer in the horizontal one
I associate the horizontal sizer to the RightPanel
I add the Left and Right panel to the main sizer.
This doesn't work...
Maybe I have missed something (mental block about sizers) but what I would like to do is to expand the notebook widget without the use of the vertical sizer inside the horizontal one (it doesn't work anyway).
So my question is. Assuming I want to expand the Notebook widget inside the RightPanel to take up the rest of the right side area of the form, how would I go about doing that?
For those that understand Erlang, This is what I have so far:
mainwindow() ->
%% Create new environment
X = wx:new(),
%% Create the main frame
MainFrame = wxFrame:new(X, -1, "Test"),
MainPanel = wxPanel:new(MainFrame, [{winid, ?wxID_ANY}]),
MainSizer = wxBoxSizer:new(?wxHORIZONTAL),
wxWindow:setSizer(MainPanel, MainSizer),
%% Left Panel...
LeftPanel = wxPanel:new(MainPanel, [{winid, ?wxID_ANY}]),
LeftPanelSizer = wxBoxSizer:new(?wxVERTICAL),
wxWindow:setSizer(LeftPanel, LeftPanelSizer),
wxWindow:setMinSize(LeftPanel, {152, -1}),
%% Right Panel
RightPanel = wxPanel:new(MainPanel, [{winid, ?wxID_ANY}]),
RightPanelVerticalSizer = wxBoxSizer:new(?wxVERTICAL),
RightPanelHorizontalSizer = wxBoxSizer:new(?wxHORIZONTAL),
wxWindow:setBackgroundColour(RightPanel, {255,0,0}),
Notebook = wxNotebook:new(RightPanel, ?wxID_ANY, [{size,{-1,-1}}]),
TestPanel1 = wxPanel:new(Notebook, [{size,{-1,-1}},{winid, ?wxID_ANY}]),
wxNotebook:addPage(Notebook, TestPanel1, "Testpanel!"),
TestPanel2 = wxPanel:new(Notebook, [{size,{-1,-1}},{winid, ?wxID_ANY}]),
wxNotebook:addPage(Notebook, TestPanel2, "Testpanel!"),
wxSizer:add(RightPanelVerticalSizer, Notebook, [{border,0},{proportion,1}, {flag,?wxEXPAND}]),
wxSizer:add(RightPanelHorizontalSizer, RightPanelVerticalSizer, [{proportion,1}, {flag,?wxEXPAND}]),
wxWindow:setSizer(RightPanel, RightPanelHorizontalSizer),
%% Main Sizer
wxSizer:add(MainSizer, LeftPanel, [{border, 2}, {flag,?wxEXPAND bor ?wxALL}]),
wxSizer:add(MainSizer, RightPanel, [{border, 2}, {flag,?wxEXPAND bor ?wxTOP bor ?wxRIGHT bor ?wxBOTTOM}]),
%% Connect to events
wxFrame:connect(MainFrame, close_window),
wxWindow:center(MainFrame),
wxWindow:show(MainFrame),
...
A:
I'm closing this question (as soon as I can) after I figured out what I needed to do.
Basically I changed the proportion to 1 of the add command to the main panel (this will expand the whole thing)
New code:
%% Main Sizer
wxSizer:add(MainSizer, LeftPanel, [{proportion,0},{border, 2}, {flag,?wxEXPAND bor ?wxALL}]),
wxSizer:add(MainSizer, RightPanel, [{proportion,1},{border, 2}, {flag,?wxEXPAND bor ?wxTOP bor ?wxRIGHT bor ?wxBOTTOM}]),
|
In erlang: How do I expand wxNotebook in a panel?
|
(I have tagged this question as Python as well since I understand Python code so examples in Python are also welcome!).
I want to create a simple window in wxWidgets:
I create a main panel which I add to a form
I associate a boxsizer to the main panel (splitting it in two, horizontally).
I add LeftPanel to the boxsizer,
I add RightPanel to the boxsizer,
I create a new boxsizer (vertical)
I create another boxsizer (horizontal)
I create a Notebook widget
I create a Panel and put it inside the Notebook (addpage)
I add the notebook to the new boxsizer (vertical one)
I add the vertical sizer in the horizontal one
I associate the horizontal sizer to the RightPanel
I add the Left and Right panel to the main sizer.
This doesn't work...
Maybe I have missed something (mental block about sizers) but what I would like to do is to expand the notebook widget without the use of the vertical sizer inside the horizontal one (it doesn't work anyway).
So my question is. Assuming I want to expand the Notebook widget inside the RightPanel to take up the rest of the right side area of the form, how would I go about doing that?
For those that understand Erlang, This is what I have so far:
mainwindow() ->
%% Create new environment
X = wx:new(),
%% Create the main frame
MainFrame = wxFrame:new(X, -1, "Test"),
MainPanel = wxPanel:new(MainFrame, [{winid, ?wxID_ANY}]),
MainSizer = wxBoxSizer:new(?wxHORIZONTAL),
wxWindow:setSizer(MainPanel, MainSizer),
%% Left Panel...
LeftPanel = wxPanel:new(MainPanel, [{winid, ?wxID_ANY}]),
LeftPanelSizer = wxBoxSizer:new(?wxVERTICAL),
wxWindow:setSizer(LeftPanel, LeftPanelSizer),
wxWindow:setMinSize(LeftPanel, {152, -1}),
%% Right Panel
RightPanel = wxPanel:new(MainPanel, [{winid, ?wxID_ANY}]),
RightPanelVerticalSizer = wxBoxSizer:new(?wxVERTICAL),
RightPanelHorizontalSizer = wxBoxSizer:new(?wxHORIZONTAL),
wxWindow:setBackgroundColour(RightPanel, {255,0,0}),
Notebook = wxNotebook:new(RightPanel, ?wxID_ANY, [{size,{-1,-1}}]),
TestPanel1 = wxPanel:new(Notebook, [{size,{-1,-1}},{winid, ?wxID_ANY}]),
wxNotebook:addPage(Notebook, TestPanel1, "Testpanel!"),
TestPanel2 = wxPanel:new(Notebook, [{size,{-1,-1}},{winid, ?wxID_ANY}]),
wxNotebook:addPage(Notebook, TestPanel2, "Testpanel!"),
wxSizer:add(RightPanelVerticalSizer, Notebook, [{border,0},{proportion,1}, {flag,?wxEXPAND}]),
wxSizer:add(RightPanelHorizontalSizer, RightPanelVerticalSizer, [{proportion,1}, {flag,?wxEXPAND}]),
wxWindow:setSizer(RightPanel, RightPanelHorizontalSizer),
%% Main Sizer
wxSizer:add(MainSizer, LeftPanel, [{border, 2}, {flag,?wxEXPAND bor ?wxALL}]),
wxSizer:add(MainSizer, RightPanel, [{border, 2}, {flag,?wxEXPAND bor ?wxTOP bor ?wxRIGHT bor ?wxBOTTOM}]),
%% Connect to events
wxFrame:connect(MainFrame, close_window),
wxWindow:center(MainFrame),
wxWindow:show(MainFrame),
...
|
[
"I'm closing this question (as soon as I can) after I figured out what I needed to do.\nBasically I changed the proportion to 1 of the add command to the main panel (this will expand the whole thing)\nNew code:\n %% Main Sizer\n wxSizer:add(MainSizer, LeftPanel, [{proportion,0},{border, 2}, {flag,?wxEXPAND bor ?wxALL}]),\n wxSizer:add(MainSizer, RightPanel, [{proportion,1},{border, 2}, {flag,?wxEXPAND bor ?wxTOP bor ?wxRIGHT bor ?wxBOTTOM}]),\n\n"
] |
[
4
] |
[] |
[] |
[
"erlang",
"layout",
"python",
"wxwidgets"
] |
stackoverflow_0001218433_erlang_layout_python_wxwidgets.txt
|
Q:
Segment a list in Python
I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have:
>>> def split_list(list, seg_length):
... inlist = list[:]
... outlist = []
...
... while inlist:
... outlist.append(inlist[0:seg_length])
... inlist[0:seg_length] = []
...
... return outlist
...
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
A:
You can use list comprehension:
>>> seg_length = 3
>>> a = range(10)
>>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
A:
How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your groups:
def split_by(sequence, length):
iterable = iter(sequence)
def yield_length():
for i in xrange(length):
yield iterable.next()
while True:
res = list(yield_length())
if not res:
return
yield res
Usage example:
>>> alist = range(10)
>>> list(split_by(alist, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
This uses far less memory than trying to construct the whole list in memory at once, if you are only looping over the result, because it only constructs one subset at a time:
>>> for subset in split_by(alist, 3):
... print subset
...
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
A:
not the same output, I still think the grouper function is helpful:
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
for Python2.4 and 2.5 that does not have izip_longest:
from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
some demo code and output:
alist = range(10)
print list(grouper(alist, 3))
output:
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
|
Segment a list in Python
|
I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have:
>>> def split_list(list, seg_length):
... inlist = list[:]
... outlist = []
...
... while inlist:
... outlist.append(inlist[0:seg_length])
... inlist[0:seg_length] = []
...
... return outlist
...
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
|
[
"You can use list comprehension:\n>>> seg_length = 3\n>>> a = range(10)\n>>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]\n[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\n",
"How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your groups:\ndef split_by(sequence, length):\n iterable = iter(sequence)\n def yield_length():\n for i in xrange(length):\n yield iterable.next()\n while True:\n res = list(yield_length())\n if not res:\n return\n yield res\n\nUsage example:\n>>> alist = range(10)\n>>> list(split_by(alist, 3))\n[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\nThis uses far less memory than trying to construct the whole list in memory at once, if you are only looping over the result, because it only constructs one subset at a time:\n>>> for subset in split_by(alist, 3):\n... print subset\n...\n[0, 1, 2]\n[3, 4, 5]\n[6, 7, 8]\n[9]\n\n",
"not the same output, I still think the grouper function is helpful:\nfrom itertools import izip_longest\ndef grouper(iterable, n, fillvalue=None):\n args = [iter(iterable)] * n\n return izip_longest(*args, fillvalue=fillvalue)\n\nfor Python2.4 and 2.5 that does not have izip_longest:\nfrom itertools import izip, chain, repeat\ndef grouper(iterable, n, padvalue=None):\n return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)\n\nsome demo code and output:\nalist = range(10)\nprint list(grouper(alist, 3))\n\noutput:\n[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]\n"
] |
[
23,
5,
2
] |
[] |
[] |
[
"list",
"python",
"segments"
] |
stackoverflow_0001218793_list_python_segments.txt
|
Q:
How to get the biggest numbers out from huge amount of numbers?
I'd like to get the largest 100 elements out from a list of at least 100000000 numbers.
I could sort the entire list and just take the last 100 elements from the sorted list, but that would be very expensive in terms of both memory and time.
Is there any existing easy, pythonic way of doing this?
What I want is following function instead of a pure sort. Actually I don't want waste time to sort the elements I don't care.
For example, this is the function I'd like to have:
getSortedElements(100, lambda x,y:cmp(x,y))
Note this requirement is only for performance perspective.
A:
The heapq module in the standard library offers the nlargest() function to do this:
top100 = heapq.nlargest(100, iterable [,key])
It won't sort the entire list, so you won't waste time on the elements you don't need.
A:
Selection algorithms should help here.
A very easy solution is to find the 100th biggest element, then run through the list picking off elements that are bigger than this element. That will give you the 100 biggest elements. This is linear in the length of the list; this is best possible.
There are more sophisticated algorithms. A heap, for example, is very amenable to this problem. The heap based algorithm is n log k where n is the length of the list and k is the number of largest elements that you want to select.
There's a discussion of this problem on the Wikipedia page for selection algorithms.
Edit: Another poster has pointed out that Python has a built in solution to this problem. Obviously that is far easier than rolling your own, but I'll keep this post up in case you would like to learn about how such algorithms work.
A:
You can use a Heap data structure. A heap will not necessarily be ordered, but it is a fairly fast way to keep semi-ordered data, and it has the benefit of the smallest item always being the first element in the heap.
A heap has two basic operations that will help you: Add and Replace.
Basically what you do is add items to it until you get to a 100 items (your top N number per your question). Then after that, you replace the first item with every new item, as long as the new item is bigger than the first item.
Whenever you replace the first item with something bigger, the internal code in the heap will adjust the heap contents so that if the new item is not the smallest, it will bubble up into the heap, and the smallest item will "bubble down" to the first element, ready to be replaced along the way.
A:
The best way to do this is to maintain a heap sorted priority queue that you pop off of once it has 100 entries in it.
While you don't care if the results are sorted it is intuitively obvious you will get this for free. In order to know you have the top 100, you need to order your current list of top numbers in order via some efficient data structure. That structure will know the minimum, the maximum, and the relative position of each element in some natural way that you can assert it's position next to it's neighbors.
As has been mentioned in python you would use heapq. In java PriorityQueue:
http://java.sun.com/javase/6/docs/api/java/util/PriorityQueue.html
A:
Here is a solution I have used that is independent of libraries and that
will work in any programming language that has arrays:
Initialisation:
Make an array of 100 elements and initialise all elements
with a low value (less than any value in your input list).
Initialise an integer variable to 0 (or any value in
[0;99]), say index_minvalue, that will point to the
current lowest value in the array.
Initialise a variable, say minvalue, to hold the current
lowest value in the array.
For each value, say current_value, in the input list:
if current_value > minvalue
Replace value in array pointed to by index_minvalue
with current_value
Find new lowest value in the array and set index_minvalue to
its array index. (linear search for this will be OK as the array
is quickly filled up with large values)
Set minvalue to current_value
else
<don't do anything!>
minvalue will quickly get a high value and thus most values
in the input list will only need to be compared to minvalue
(the result of the comparison will mostly be false).
A:
For the algorithms weenies in the audience: you can do this with a simple variation on Tony Hoare's algorithm Find:
find(topn, a, i, j)
pick a random element x from a[i..j]
partition the subarray a[i..j] (just as in Quicksort)
into subarrays of elements <x, ==x, >x
let k be the position of element x
if k == 0 you're finished
if k > topn, call find(topn, a, i, k)
if k < topn, call find(topn-k, k, j)
This algorithm puts the largest topn elements into the first topn elements of array a, without sorting them. Of course, if you want them sorted, or for sheer simplicity, a heap is better, and calling the library function is better still. But it's a cool algorithm.
|
How to get the biggest numbers out from huge amount of numbers?
|
I'd like to get the largest 100 elements out from a list of at least 100000000 numbers.
I could sort the entire list and just take the last 100 elements from the sorted list, but that would be very expensive in terms of both memory and time.
Is there any existing easy, pythonic way of doing this?
What I want is following function instead of a pure sort. Actually I don't want waste time to sort the elements I don't care.
For example, this is the function I'd like to have:
getSortedElements(100, lambda x,y:cmp(x,y))
Note this requirement is only for performance perspective.
|
[
"The heapq module in the standard library offers the nlargest() function to do this:\ntop100 = heapq.nlargest(100, iterable [,key])\n\nIt won't sort the entire list, so you won't waste time on the elements you don't need.\n",
"Selection algorithms should help here. \nA very easy solution is to find the 100th biggest element, then run through the list picking off elements that are bigger than this element. That will give you the 100 biggest elements. This is linear in the length of the list; this is best possible.\nThere are more sophisticated algorithms. A heap, for example, is very amenable to this problem. The heap based algorithm is n log k where n is the length of the list and k is the number of largest elements that you want to select.\nThere's a discussion of this problem on the Wikipedia page for selection algorithms.\nEdit: Another poster has pointed out that Python has a built in solution to this problem. Obviously that is far easier than rolling your own, but I'll keep this post up in case you would like to learn about how such algorithms work.\n",
"You can use a Heap data structure. A heap will not necessarily be ordered, but it is a fairly fast way to keep semi-ordered data, and it has the benefit of the smallest item always being the first element in the heap.\nA heap has two basic operations that will help you: Add and Replace.\nBasically what you do is add items to it until you get to a 100 items (your top N number per your question). Then after that, you replace the first item with every new item, as long as the new item is bigger than the first item.\nWhenever you replace the first item with something bigger, the internal code in the heap will adjust the heap contents so that if the new item is not the smallest, it will bubble up into the heap, and the smallest item will \"bubble down\" to the first element, ready to be replaced along the way.\n",
"The best way to do this is to maintain a heap sorted priority queue that you pop off of once it has 100 entries in it. \nWhile you don't care if the results are sorted it is intuitively obvious you will get this for free. In order to know you have the top 100, you need to order your current list of top numbers in order via some efficient data structure. That structure will know the minimum, the maximum, and the relative position of each element in some natural way that you can assert it's position next to it's neighbors. \nAs has been mentioned in python you would use heapq. In java PriorityQueue:\nhttp://java.sun.com/javase/6/docs/api/java/util/PriorityQueue.html \n",
"Here is a solution I have used that is independent of libraries and that\nwill work in any programming language that has arrays:\nInitialisation:\nMake an array of 100 elements and initialise all elements\nwith a low value (less than any value in your input list).\n\nInitialise an integer variable to 0 (or any value in\n[0;99]), say index_minvalue, that will point to the\ncurrent lowest value in the array.\n\nInitialise a variable, say minvalue, to hold the current \nlowest value in the array.\n\nFor each value, say current_value, in the input list:\nif current_value > minvalue\n\n Replace value in array pointed to by index_minvalue\n with current_value\n\n Find new lowest value in the array and set index_minvalue to\n its array index. (linear search for this will be OK as the array\n is quickly filled up with large values)\n\n Set minvalue to current_value\n\nelse\n <don't do anything!>\n\nminvalue will quickly get a high value and thus most values\nin the input list will only need to be compared to minvalue\n(the result of the comparison will mostly be false).\n",
"For the algorithms weenies in the audience: you can do this with a simple variation on Tony Hoare's algorithm Find:\nfind(topn, a, i, j)\n pick a random element x from a[i..j]\n partition the subarray a[i..j] (just as in Quicksort) \n into subarrays of elements <x, ==x, >x\n let k be the position of element x\n if k == 0 you're finished\n if k > topn, call find(topn, a, i, k)\n if k < topn, call find(topn-k, k, j)\n\nThis algorithm puts the largest topn elements into the first topn elements of array a, without sorting them. Of course, if you want them sorted, or for sheer simplicity, a heap is better, and calling the library function is better still. But it's a cool algorithm.\n"
] |
[
27,
6,
5,
3,
2,
1
] |
[] |
[] |
[
"max",
"minimum",
"python",
"sorting"
] |
stackoverflow_0001218922_max_minimum_python_sorting.txt
|
Q:
Trappings MySQL Warnings on Calls Wrapped in Classes -- Python
I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes.
I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries through that cursor object. The cursor is itself wrapped in a class. These seem to run queries properly, but the MySQL warnings they generate are not caught as exceptions in a try/else block. Why don't the try/else blocks catch the warnings? How would I revise the classes or method calls to catch the warnings?
Also, I've looked through the prominent sources and can't find a discussion that helps me understand this. I'd appreciate any reference that explains this.
Please see code below. Apologies for verbosity, I'm newbie.
#!/usr/bin/python
import MySQLdb
import sys
import copy
sys.path.append('../../config')
import credentials as c # local module with dbase connection credentials
#=============================================================================
# CLASSES
#------------------------------------------------------------------------
class dbMySQL_Connection:
def __init__(self, db_server, db_user, db_passwd):
self.conn = MySQLdb.connect(db_server, db_user, db_passwd)
def getCursor(self, dict_flag=True):
self.dbMySQL_Cursor = dbMySQL_Cursor(self.conn, dict_flag)
return self.dbMySQL_Cursor
def runQuery(self, qryStr, dict_flag=True):
qry_res = runQueryNoCursor(qryStr=qryStr, \
conn=self, \
dict_flag=dict_flag)
return qry_res
#------------------------------------------------------------------------
class dbMySQL_Cursor:
def __init__(self, conn, dict_flag=True):
if dict_flag:
dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)
else:
dbMySQL_Cursor = conn.cursor()
self.dbMySQL_Cursor = dbMySQL_Cursor
def closeCursor(self):
self.dbMySQL_Cursor.close()
#=============================================================================
# QUERY FUNCTIONS
#------------------------------------------------------------------------------
def runQueryNoCursor(qryStr, conn, dict_flag=True):
dbMySQL_Cursor = conn.getCursor(dict_flag)
qry_res =runQueryFnc(qryStr, dbMySQL_Cursor.dbMySQL_Cursor)
dbMySQL_Cursor.closeCursor()
return qry_res
#------------------------------------------------------------------------------
def runQueryFnc(qryStr, dbMySQL_Cursor):
qry_res = {}
qry_res['rows'] = dbMySQL_Cursor.execute(qryStr)
qry_res['result'] = copy.deepcopy(dbMySQL_Cursor.fetchall())
qry_res['messages'] = copy.deepcopy(dbMySQL_Cursor.messages)
qry_res['query_str'] = qryStr
return qry_res
#=============================================================================
# USAGES
qry = 'DROP DATABASE IF EXISTS database_of_armaments'
dbConn = dbMySQL_Connection(**c.creds)
def dbConnRunQuery():
# Does not trap an exception; warning displayed to standard error.
try:
dbConn.runQuery(qry)
except:
print "dbConn.runQuery() caught an exception."
def dbConnCursorExecute():
# Does not trap an exception; warning displayed to standard error.
dbConn.getCursor() # try/except block does catches error without this
try:
dbConn.dbMySQL_Cursor.dbMySQL_Cursor.execute(qry)
except Exception, e:
print "dbConn.dbMySQL_Cursor.execute() caught an exception."
print repr(e)
def funcRunQueryNoCursor():
# Does not trap an exception; no warning displayed
try:
res = runQueryNoCursor(qry, dbConn)
print 'Try worked. %s' % res
except Exception, e:
print "funcRunQueryNoCursor() caught an exception."
print repr(e)
#=============================================================================
if __name__ == '__main__':
print '\n'
print 'EXAMPLE -- dbConnRunQuery()'
dbConnRunQuery()
print '\n'
print 'EXAMPLE -- dbConnCursorExecute()'
dbConnCursorExecute()
print '\n'
print 'EXAMPLE -- funcRunQueryNoCursor()'
funcRunQueryNoCursor()
print '\n'
A:
On first glance at least one problem:
if dict_flag:
dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)
shouldn't that be
if dict_flag:
self.dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)
You're mixing your self/not self. Also I would wrap the
self.conn = MySQLdb.connect(db_server, db_user, db_passwd)
in a try/except block since I have a suspicion you may not be creating the database connection properly due to the import of db credentials (I'd toss in a print statement to make sure the data is actually being passed).
|
Trappings MySQL Warnings on Calls Wrapped in Classes -- Python
|
I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes.
I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries through that cursor object. The cursor is itself wrapped in a class. These seem to run queries properly, but the MySQL warnings they generate are not caught as exceptions in a try/else block. Why don't the try/else blocks catch the warnings? How would I revise the classes or method calls to catch the warnings?
Also, I've looked through the prominent sources and can't find a discussion that helps me understand this. I'd appreciate any reference that explains this.
Please see code below. Apologies for verbosity, I'm newbie.
#!/usr/bin/python
import MySQLdb
import sys
import copy
sys.path.append('../../config')
import credentials as c # local module with dbase connection credentials
#=============================================================================
# CLASSES
#------------------------------------------------------------------------
class dbMySQL_Connection:
def __init__(self, db_server, db_user, db_passwd):
self.conn = MySQLdb.connect(db_server, db_user, db_passwd)
def getCursor(self, dict_flag=True):
self.dbMySQL_Cursor = dbMySQL_Cursor(self.conn, dict_flag)
return self.dbMySQL_Cursor
def runQuery(self, qryStr, dict_flag=True):
qry_res = runQueryNoCursor(qryStr=qryStr, \
conn=self, \
dict_flag=dict_flag)
return qry_res
#------------------------------------------------------------------------
class dbMySQL_Cursor:
def __init__(self, conn, dict_flag=True):
if dict_flag:
dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)
else:
dbMySQL_Cursor = conn.cursor()
self.dbMySQL_Cursor = dbMySQL_Cursor
def closeCursor(self):
self.dbMySQL_Cursor.close()
#=============================================================================
# QUERY FUNCTIONS
#------------------------------------------------------------------------------
def runQueryNoCursor(qryStr, conn, dict_flag=True):
dbMySQL_Cursor = conn.getCursor(dict_flag)
qry_res =runQueryFnc(qryStr, dbMySQL_Cursor.dbMySQL_Cursor)
dbMySQL_Cursor.closeCursor()
return qry_res
#------------------------------------------------------------------------------
def runQueryFnc(qryStr, dbMySQL_Cursor):
qry_res = {}
qry_res['rows'] = dbMySQL_Cursor.execute(qryStr)
qry_res['result'] = copy.deepcopy(dbMySQL_Cursor.fetchall())
qry_res['messages'] = copy.deepcopy(dbMySQL_Cursor.messages)
qry_res['query_str'] = qryStr
return qry_res
#=============================================================================
# USAGES
qry = 'DROP DATABASE IF EXISTS database_of_armaments'
dbConn = dbMySQL_Connection(**c.creds)
def dbConnRunQuery():
# Does not trap an exception; warning displayed to standard error.
try:
dbConn.runQuery(qry)
except:
print "dbConn.runQuery() caught an exception."
def dbConnCursorExecute():
# Does not trap an exception; warning displayed to standard error.
dbConn.getCursor() # try/except block does catches error without this
try:
dbConn.dbMySQL_Cursor.dbMySQL_Cursor.execute(qry)
except Exception, e:
print "dbConn.dbMySQL_Cursor.execute() caught an exception."
print repr(e)
def funcRunQueryNoCursor():
# Does not trap an exception; no warning displayed
try:
res = runQueryNoCursor(qry, dbConn)
print 'Try worked. %s' % res
except Exception, e:
print "funcRunQueryNoCursor() caught an exception."
print repr(e)
#=============================================================================
if __name__ == '__main__':
print '\n'
print 'EXAMPLE -- dbConnRunQuery()'
dbConnRunQuery()
print '\n'
print 'EXAMPLE -- dbConnCursorExecute()'
dbConnCursorExecute()
print '\n'
print 'EXAMPLE -- funcRunQueryNoCursor()'
funcRunQueryNoCursor()
print '\n'
|
[
"On first glance at least one problem:\n if dict_flag:\n dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)\n\nshouldn't that be\n if dict_flag:\n self.dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)\n\nYou're mixing your self/not self. Also I would wrap the \nself.conn = MySQLdb.connect(db_server, db_user, db_passwd)\n\nin a try/except block since I have a suspicion you may not be creating the database connection properly due to the import of db credentials (I'd toss in a print statement to make sure the data is actually being passed). \n"
] |
[
0
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0000651358_mysql_python.txt
|
Q:
Multiprocessing Debugging error
Hey everyone, I am having a little trouble debugging my code. Please look below:
import globalFunc
from globalFunc import systemPrint
from globalFunc import out
from globalFunc import debug
import math
import time
import multiprocessing
"""
Somehow this is not working well
"""
class urlServerM( multiprocessing.Process):
"""
This calculates how much links get put into the priority queue
so to reach the level that we intend, for every query resultset,
we will put the a certain number of links into visitNext first,
and even if every resultSet is full, we will be able to achieve the link
level that we intended. The rest is pushed into another list where
if the first set of lists don't have max for every time, the remaining will
be spared on these links
"""
def getPriorityCounter(self, level, constraint):
return int( math.exp( ( math.log(constraint) / (level - 1) ) ) )
def __init__( self, level, constraint, urlQ):
"""limit is obtained via ngCrawler.getPriorityNum"""
multiprocessing.Process.__init__(self)
self.constraint = int( constraint)
self.limit = self.getPriorityCounter( level, self.constraint)
self.visitNext = []
self.visitLater = []
self._count = 0
self.urlQ = urlQ
"""
puts the next into the Queue
"""
def putNextIntoQ(self):
debug('putNextIntoQ', str(self.visitNext) + str(self.visitLater) )
if self.visitNext != []:
_tmp = self.visitNext[0]
self.visitNext.remove(_tmp)
self.urlQ.put(_tmp)
elif self.visitLater != []:
_tmp = self.visitLater[0]
self.visitLater.remove(_tmp)
self.urlQ.put(_tmp)
def run(self):
while True:
if self.hasNext():
time.sleep(0.5)
self.putNextIntoQ()
debug('process', 'put something in Q already')
else:
out('process', 'Nothing in visitNext or visitLater, sleeping')
time.sleep(2)
return
def hasNext(self):
debug( 'hasnext', str(self.visitNext) + str(self.visitLater) )
if self.visitNext != []:
return True
elif self.visitLater != []:
return True
return False
"""
This function resets the counter
which is used to keep track of how much is already inside the
visitNext vs visitLater
"""
def reset(self):
self._count = 0
def store(self, linkS):
"""Stores a link into one of these list"""
if self._count < self.limit:
self.visitNext.append( linkS)
debug('put', 'something is put inside visitNext')
else:
self.visitLater.append( linkS)
debug('put', 'something is put inside visitLater')
self._count += 1
if __name__ == "__main__":
# def __init__( self, level, constraint, urlQ):
from multiprocessing import Queue
q = Queue(3)
us = urlServerM( 3, 6000, q)
us.start()
time.sleep(2)
# only one thread will do this
us.store('http://www.google.com')
debug('put', 'put completed')
time.sleep(3)
print q.get_nowait()
time.sleep(3)
And this is the output
OUTPUT
DEBUG hasnext: [][]
[process] Nothing in visitNext or visitLater, sleeping
DEBUG put: something is put inside visitNext
DEBUG put: put completed
DEBUG hasnext: [][]
[process] Nothing in visitNext or visitLater, sleeping
DEBUG hasnext: [][]
[process] Nothing in visitNext or visitLater, sleeping
Traceback (most recent call last):
File "urlServerM.py", line 112, in <module>
print q.get_nowait()
File "/usr/lib/python2.6/multiprocessing/queues.py", line 122, in get_nowait
return self.get(False)
File "/usr/lib/python2.6/multiprocessing/queues.py", line 104, in get
raise Empty
Queue.Empty
DEBUG hasnext: [][]
Apparently, I find this really weird. Well basically what this code this is that when tested in main(), it starts the process, and then it stores http://www.google.com into the the class's visitNext, and then I just want to see that being pushed into the Queue.
However, according to the output
I find it extremely weird that even though my class has completed storing a url into the Class, hasNext doesn't show anything up. Any body know why? Is this the best way to write run() in a continual while loop? Is this actually necessary? I basically am trying to experiment with the module multiprocessing, and I have a pool of workers (from multiprocessing.Pool) which need to obtain these urls from this class (Single point of entry). Is using a queue the best way? Do I need to make this a "live" process since every worker is asking from the Queue and unless I have a way to signal that to my urlServer to put something into the Queue, I cannot think of a less troublesome way.
A:
You're using multiprocessing, so the memory is not shared between main execution and your urlserver.
I.e. I think this is effectively a Noop: {us.store('http://www.google.com')} because when it's executed in the main thread, it modifies only the main threads representation of {us}. You can confirm that the url is in main thread's memory, by calling {us.hasnext()} before {q.get_nowait()}.
To make it work, you'll have to turn all lists that you want to share into Queue-s, or Pipe-s. Alternatively, you can just change your model to {threading} and it should work without changes (more or less - you'll have to do locking around the visit lists; and you get GIL issues again).
(And yeah - please edit your questions better next time. I knew what might be your problem as soon as I saw "multiprocessing", but otherwise I wouldn't bother looking at the code at all...)
|
Multiprocessing Debugging error
|
Hey everyone, I am having a little trouble debugging my code. Please look below:
import globalFunc
from globalFunc import systemPrint
from globalFunc import out
from globalFunc import debug
import math
import time
import multiprocessing
"""
Somehow this is not working well
"""
class urlServerM( multiprocessing.Process):
"""
This calculates how much links get put into the priority queue
so to reach the level that we intend, for every query resultset,
we will put the a certain number of links into visitNext first,
and even if every resultSet is full, we will be able to achieve the link
level that we intended. The rest is pushed into another list where
if the first set of lists don't have max for every time, the remaining will
be spared on these links
"""
def getPriorityCounter(self, level, constraint):
return int( math.exp( ( math.log(constraint) / (level - 1) ) ) )
def __init__( self, level, constraint, urlQ):
"""limit is obtained via ngCrawler.getPriorityNum"""
multiprocessing.Process.__init__(self)
self.constraint = int( constraint)
self.limit = self.getPriorityCounter( level, self.constraint)
self.visitNext = []
self.visitLater = []
self._count = 0
self.urlQ = urlQ
"""
puts the next into the Queue
"""
def putNextIntoQ(self):
debug('putNextIntoQ', str(self.visitNext) + str(self.visitLater) )
if self.visitNext != []:
_tmp = self.visitNext[0]
self.visitNext.remove(_tmp)
self.urlQ.put(_tmp)
elif self.visitLater != []:
_tmp = self.visitLater[0]
self.visitLater.remove(_tmp)
self.urlQ.put(_tmp)
def run(self):
while True:
if self.hasNext():
time.sleep(0.5)
self.putNextIntoQ()
debug('process', 'put something in Q already')
else:
out('process', 'Nothing in visitNext or visitLater, sleeping')
time.sleep(2)
return
def hasNext(self):
debug( 'hasnext', str(self.visitNext) + str(self.visitLater) )
if self.visitNext != []:
return True
elif self.visitLater != []:
return True
return False
"""
This function resets the counter
which is used to keep track of how much is already inside the
visitNext vs visitLater
"""
def reset(self):
self._count = 0
def store(self, linkS):
"""Stores a link into one of these list"""
if self._count < self.limit:
self.visitNext.append( linkS)
debug('put', 'something is put inside visitNext')
else:
self.visitLater.append( linkS)
debug('put', 'something is put inside visitLater')
self._count += 1
if __name__ == "__main__":
# def __init__( self, level, constraint, urlQ):
from multiprocessing import Queue
q = Queue(3)
us = urlServerM( 3, 6000, q)
us.start()
time.sleep(2)
# only one thread will do this
us.store('http://www.google.com')
debug('put', 'put completed')
time.sleep(3)
print q.get_nowait()
time.sleep(3)
And this is the output
OUTPUT
DEBUG hasnext: [][]
[process] Nothing in visitNext or visitLater, sleeping
DEBUG put: something is put inside visitNext
DEBUG put: put completed
DEBUG hasnext: [][]
[process] Nothing in visitNext or visitLater, sleeping
DEBUG hasnext: [][]
[process] Nothing in visitNext or visitLater, sleeping
Traceback (most recent call last):
File "urlServerM.py", line 112, in <module>
print q.get_nowait()
File "/usr/lib/python2.6/multiprocessing/queues.py", line 122, in get_nowait
return self.get(False)
File "/usr/lib/python2.6/multiprocessing/queues.py", line 104, in get
raise Empty
Queue.Empty
DEBUG hasnext: [][]
Apparently, I find this really weird. Well basically what this code this is that when tested in main(), it starts the process, and then it stores http://www.google.com into the the class's visitNext, and then I just want to see that being pushed into the Queue.
However, according to the output
I find it extremely weird that even though my class has completed storing a url into the Class, hasNext doesn't show anything up. Any body know why? Is this the best way to write run() in a continual while loop? Is this actually necessary? I basically am trying to experiment with the module multiprocessing, and I have a pool of workers (from multiprocessing.Pool) which need to obtain these urls from this class (Single point of entry). Is using a queue the best way? Do I need to make this a "live" process since every worker is asking from the Queue and unless I have a way to signal that to my urlServer to put something into the Queue, I cannot think of a less troublesome way.
|
[
"You're using multiprocessing, so the memory is not shared between main execution and your urlserver.\nI.e. I think this is effectively a Noop: {us.store('http://www.google.com')} because when it's executed in the main thread, it modifies only the main threads representation of {us}. You can confirm that the url is in main thread's memory, by calling {us.hasnext()} before {q.get_nowait()}.\nTo make it work, you'll have to turn all lists that you want to share into Queue-s, or Pipe-s. Alternatively, you can just change your model to {threading} and it should work without changes (more or less - you'll have to do locking around the visit lists; and you get GIL issues again).\n(And yeah - please edit your questions better next time. I knew what might be your problem as soon as I saw \"multiprocessing\", but otherwise I wouldn't bother looking at the code at all...)\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001218757_python.txt
|
Q:
Workarounds when a string is too long for a .join. OverflowError occurs
I'm working through some python problems on pythonchallenge.com to teach myself python and I've hit a roadblock, since the string I am to be using is too large for python to handle. I receive this error:
my-macbook:python owner1$ python singleoccurrence.py
Traceback (most recent call last):
File "singleoccurrence.py", line 32, in <module>
myString = myString.join(line)
OverflowError: join() result is too long for a Python string
What alternatives do I have for this issue? My code looks like such...
#open file testdata.txt
#for each character, check if already exists in array of checked characters
#if so, skip.
#if not, character.count
#if count > 1, repeat recursively with first character stripped off of page.
# if count = 1, add to valid character array.
#when string = 0, print valid character array.
valid = []
checked = []
myString = ""
def recursiveCount(bigString):
if len(bigString) == 0:
print "YAY!"
return valid
myChar = bigString[0]
if myChar in checked:
return recursiveCount(bigString[1:])
if bigString.count(myChar) > 1:
checked.append(myChar)
return recursiveCount(bigString[1:])
checked.append(myChar)
valid.append(myChar)
return recursiveCount(bigString[1:])
fileIN = open("testdata.txt", "r")
line = fileIN.readline()
while line:
line = line.strip()
myString = myString.join(line)
line = fileIN.readline()
myString = recursiveCount(myString)
print "\n"
print myString
A:
string.join doesn't do what you think. join is used to combine a list of words into a single string with the given seperator. Ie:
>>> ",".join(('foo', 'bar', 'baz'))
'foo,bar,baz'
The code snippet you posted will attempt to insert myString between every character in the variable line. You can see how that will get big quickly :-). Are you trying to read the entire file into a single string, myString? If so, the way you want to concatenate the strings is like this:
myString = myString + line
While I'm here... since you're learning Python here are some other suggestions.
There are easier ways to read an entire file into a variable. For instance:
fileIN = open("testdata.txt", "r")
myString = fileIN.read()
(This won't have the exact behaviour of your existing strip() code, but may in fact do what you want.)
Also, I would never recommend practical Python code use recursion to iterate over a string. Your code will make a function call (and a stack entry) for every character in the string. Also I'm not sure Python will be very smart about all the uses of bigString[1:]: it may well create a second string in memory that's a copy of the original without the first character. The simplest way to process every character in a string is:
for mychar in bigString:
... do your stuff ...
Finally, you are using the list named "checked" to see if you've ever seen a particular character before. But the membership test on lists ("if myChar in checked") is slow. In Python you're better off using a dictionary:
checked = {}
...
if not checked.has_key(myChar):
checked[myChar] = True
...
This exercise you're doing is a great way to learn several Python idioms.
|
Workarounds when a string is too long for a .join. OverflowError occurs
|
I'm working through some python problems on pythonchallenge.com to teach myself python and I've hit a roadblock, since the string I am to be using is too large for python to handle. I receive this error:
my-macbook:python owner1$ python singleoccurrence.py
Traceback (most recent call last):
File "singleoccurrence.py", line 32, in <module>
myString = myString.join(line)
OverflowError: join() result is too long for a Python string
What alternatives do I have for this issue? My code looks like such...
#open file testdata.txt
#for each character, check if already exists in array of checked characters
#if so, skip.
#if not, character.count
#if count > 1, repeat recursively with first character stripped off of page.
# if count = 1, add to valid character array.
#when string = 0, print valid character array.
valid = []
checked = []
myString = ""
def recursiveCount(bigString):
if len(bigString) == 0:
print "YAY!"
return valid
myChar = bigString[0]
if myChar in checked:
return recursiveCount(bigString[1:])
if bigString.count(myChar) > 1:
checked.append(myChar)
return recursiveCount(bigString[1:])
checked.append(myChar)
valid.append(myChar)
return recursiveCount(bigString[1:])
fileIN = open("testdata.txt", "r")
line = fileIN.readline()
while line:
line = line.strip()
myString = myString.join(line)
line = fileIN.readline()
myString = recursiveCount(myString)
print "\n"
print myString
|
[
"string.join doesn't do what you think. join is used to combine a list of words into a single string with the given seperator. Ie:\n>>> \",\".join(('foo', 'bar', 'baz'))\n'foo,bar,baz'\n\nThe code snippet you posted will attempt to insert myString between every character in the variable line. You can see how that will get big quickly :-). Are you trying to read the entire file into a single string, myString? If so, the way you want to concatenate the strings is like this:\nmyString = myString + line\n\nWhile I'm here... since you're learning Python here are some other suggestions.\nThere are easier ways to read an entire file into a variable. For instance:\nfileIN = open(\"testdata.txt\", \"r\")\nmyString = fileIN.read()\n\n(This won't have the exact behaviour of your existing strip() code, but may in fact do what you want.)\nAlso, I would never recommend practical Python code use recursion to iterate over a string. Your code will make a function call (and a stack entry) for every character in the string. Also I'm not sure Python will be very smart about all the uses of bigString[1:]: it may well create a second string in memory that's a copy of the original without the first character. The simplest way to process every character in a string is:\nfor mychar in bigString:\n ... do your stuff ...\n\nFinally, you are using the list named \"checked\" to see if you've ever seen a particular character before. But the membership test on lists (\"if myChar in checked\") is slow. In Python you're better off using a dictionary:\nchecked = {}\n...\nif not checked.has_key(myChar):\n checked[myChar] = True\n ...\n\nThis exercise you're doing is a great way to learn several Python idioms.\n"
] |
[
10
] |
[] |
[] |
[
"overflow",
"python"
] |
stackoverflow_0001219733_overflow_python.txt
|
Q:
Python: prefer several small modules or one larger module?
I'm working on a Python web application in which I have some small modules that serve very specific functions: session.py, logger.py, database.py, etc. And by "small" I really do mean small; each of these files currently includes around 3-5 lines of code, or maybe up to 10 at most. I might have a few imports and a class definition or two in each. I'm wondering, is there any reason I should or shouldn't merge these into one module, something like misc.py?
My thoughts are that having separate modules helps with code clarity, and later on, if by some chance these modules grow to more than 10 lines, I won't feel so bad about having them separated. But on the other hand, it just seems like such a waste to have a bunch of files with only a few lines in each! And is there any significant difference in resource usage between the multi-file vs. single-file approach? (Of course I'm nowhere near the point where I should be worrying about resource usage, but I couldn't resist asking...)
I checked around to see whether this had been asked before and didn't see anything specific to Python, but if it's in fact a duplicate, I'd appreciate being pointed in the right direction.
A:
My thoughts are that having separate
modules helps with code clarity, and
later on, if by some chance these
modules grow to more than 10 lines, I
won't feel so bad about having them
separated.
This. Keep it the way you have it.
A:
As a user of modules, I greatly prefer when I can include the entire module via a single import. Don't make a user of your package do multiple imports unless there's some reason to allow for importing different alternates.
BTW, there's no reason a single modules can't consist of multiple source files. The simplest case is to use an __init__.py file to simply load all the other code into the module's namespace.
A:
Personally I find it easier to keep things like this in a single file, just for the practicality of editing a smaller number of files in my editor.
The important thing to do is treat the different pieces of code as though they were in separate files, so you ensure that you can trivially separate them later, for the reasons you cite. So for instance, don't introduce dependencies between the different pieces that will make it hard to disentangle them later.
A:
For command line scripts there most likely will not be much difference unless each invocation invokes all files in the module, in which case there will be a slight performance cost as n files need to be opened vs one.
For mod_python there most likely will be no difference as byte-compiled modules stay alive for the duration of the apache process.
For google app engine though there will be a performance hit unless the service is constantly used and is "hot" as each cold start would require opening all files.
A:
Off course you can have as many modules as you like.
But now let as think a little, what happens when we put every small code snippet into one single file.
We will end up in hundreds of import statements in any less trivial module. And off course you could also save a little by having all explicit in seperated files. But guess what: Nobody can remember so many module names and you might end up in searching for the right file anyway ...
I try to put things that belong together in one single file (unless it becomes to big!). But when I have small functions or classes that do not belong to other components in my system, I have "util" modules or the like. I also try to group these for example according to my application layering or seperate them by other means. One seperation criteria could be: Utilities that are used for UI and those that are not.
|
Python: prefer several small modules or one larger module?
|
I'm working on a Python web application in which I have some small modules that serve very specific functions: session.py, logger.py, database.py, etc. And by "small" I really do mean small; each of these files currently includes around 3-5 lines of code, or maybe up to 10 at most. I might have a few imports and a class definition or two in each. I'm wondering, is there any reason I should or shouldn't merge these into one module, something like misc.py?
My thoughts are that having separate modules helps with code clarity, and later on, if by some chance these modules grow to more than 10 lines, I won't feel so bad about having them separated. But on the other hand, it just seems like such a waste to have a bunch of files with only a few lines in each! And is there any significant difference in resource usage between the multi-file vs. single-file approach? (Of course I'm nowhere near the point where I should be worrying about resource usage, but I couldn't resist asking...)
I checked around to see whether this had been asked before and didn't see anything specific to Python, but if it's in fact a duplicate, I'd appreciate being pointed in the right direction.
|
[
"\nMy thoughts are that having separate\n modules helps with code clarity, and\n later on, if by some chance these\n modules grow to more than 10 lines, I\n won't feel so bad about having them\n separated.\n\nThis. Keep it the way you have it. \n",
"As a user of modules, I greatly prefer when I can include the entire module via a single import. Don't make a user of your package do multiple imports unless there's some reason to allow for importing different alternates.\nBTW, there's no reason a single modules can't consist of multiple source files. The simplest case is to use an __init__.py file to simply load all the other code into the module's namespace.\n",
"Personally I find it easier to keep things like this in a single file, just for the practicality of editing a smaller number of files in my editor.\nThe important thing to do is treat the different pieces of code as though they were in separate files, so you ensure that you can trivially separate them later, for the reasons you cite. So for instance, don't introduce dependencies between the different pieces that will make it hard to disentangle them later.\n",
"For command line scripts there most likely will not be much difference unless each invocation invokes all files in the module, in which case there will be a slight performance cost as n files need to be opened vs one.\nFor mod_python there most likely will be no difference as byte-compiled modules stay alive for the duration of the apache process.\nFor google app engine though there will be a performance hit unless the service is constantly used and is \"hot\" as each cold start would require opening all files.\n",
"Off course you can have as many modules as you like.\nBut now let as think a little, what happens when we put every small code snippet into one single file.\nWe will end up in hundreds of import statements in any less trivial module. And off course you could also save a little by having all explicit in seperated files. But guess what: Nobody can remember so many module names and you might end up in searching for the right file anyway ...\nI try to put things that belong together in one single file (unless it becomes to big!). But when I have small functions or classes that do not belong to other components in my system, I have \"util\" modules or the like. I also try to group these for example according to my application layering or seperate them by other means. One seperation criteria could be: Utilities that are used for UI and those that are not.\n"
] |
[
9,
7,
3,
3,
2
] |
[
"Small. \n"
] |
[
-2
] |
[
"module",
"python",
"refactoring"
] |
stackoverflow_0001219815_module_python_refactoring.txt
|
Q:
Filter and sort music info on Google App Engine
I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another.
Let's assume the core model is an Album that contains several properties, including:
Title
Artist
Label
Publication Year
Genre
Length
List of track names
List of moods
Datetime of insertion into database
Let's also assume that I would like to filter the entire collection using those properties, and then sorting the results by one of:
Publication year
Length of album
Artist name
When the info was added into the database
I don't know how to do this without running into the exploding index conundrum. Specifically, I'd love to do something like:
Albums.all().filter('publication_year <', 1980).order('artist_name')
I know that's not possible, but what's the workaround?
This seems like a fairly general type of application. The music albums could be restaurants, bottles of wine, or hotels. I have a collection of items with descriptive properties that I'd like to filter and sort.
Is there a best practice data model design that I'm overlooking? Any advice?
A:
There's a couple of options here: You can filter as best as possible, then sort the results in memory, as Alex suggests, or you can rework your data structures for equality filters instead of inequality filters.
For example, assuming you only want to filter by decade, you can add a field encoding the decade in which the song was recorded. To find everything before or after a decade, do an IN query for the decades you want to span. This will require one underlying query per decade included, but if the number of records is large, this can still be cheaper than fetching all the results and sorting them in memory.
A:
Since storage is cheap, you could create your own ListProperty based indexfiles with key_names that reflect the sort criteria.
class album_pubyear_List(db.Model):
words = db.StringListProperty()
class album_length_List(db.Model):
words = db.StringListProperty()
class album_artist_List(db.Model):
words = db.StringListProperty()
class Album(db.Model):
blah...
def save(self):
super(Album, self).save()
# you could do this at save time or batch it and do
# it with a cronjob or taskqueue
words = []
for field in ["title", "artist", "label", "genre", ...]:
words.append("%s:%s" %(field, getattr(self, field)))
word_records = []
now = repr(time.time())
word_records.append(album_pubyear_List(parent=self, key_name="%s_%s" %(self.pubyear, now)), words=words)
word_records.append(album_length_List(parent=self, key_name="%s_%s" %(self.album_length, now)), words=words)
word_records.append(album_artist_List(parent=self, key_name="%s_%s" %(self.artist_name, now)), words=words)
db.put(word_records)
Now when it's time to search you create an appropriate WHERE clause and call the appropriate model
where = "WHERE words = " + "%s:%s" %(field-a, value-a) + " AND " + "%s:%s" %(field-b, value-b) etc.
aModel = "album_pubyear_List" # or anyone of the other key_name sorted wordlist models
indexes = db.GqlQuery("""SELECT __key__ from %s %s""" %(aModel, where))
keys = [k.parent() for k in indexes[offset:numresults+1]] # +1 for pagination
object_list = db.get(keys) # returns a sorted by key_name list of Albums
A:
As you say, you can't have an inequality condition on one field and an order by another (or inequalities on two fields, etc, etc). The workaround is simply to use the "best" inequality condition to get data in memory (where "best" means the one that's expected to yield the least data) and then further refine it and order it by Python code in your application.
Python's list comprehensions (and other forms of loops &c), list's sort method and the sorted built-in function, the itertools module in the standard library, and so on, all help a lot to make these kinds of tasks quite simple to perform in Python itself.
|
Filter and sort music info on Google App Engine
|
I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another.
Let's assume the core model is an Album that contains several properties, including:
Title
Artist
Label
Publication Year
Genre
Length
List of track names
List of moods
Datetime of insertion into database
Let's also assume that I would like to filter the entire collection using those properties, and then sorting the results by one of:
Publication year
Length of album
Artist name
When the info was added into the database
I don't know how to do this without running into the exploding index conundrum. Specifically, I'd love to do something like:
Albums.all().filter('publication_year <', 1980).order('artist_name')
I know that's not possible, but what's the workaround?
This seems like a fairly general type of application. The music albums could be restaurants, bottles of wine, or hotels. I have a collection of items with descriptive properties that I'd like to filter and sort.
Is there a best practice data model design that I'm overlooking? Any advice?
|
[
"There's a couple of options here: You can filter as best as possible, then sort the results in memory, as Alex suggests, or you can rework your data structures for equality filters instead of inequality filters.\nFor example, assuming you only want to filter by decade, you can add a field encoding the decade in which the song was recorded. To find everything before or after a decade, do an IN query for the decades you want to span. This will require one underlying query per decade included, but if the number of records is large, this can still be cheaper than fetching all the results and sorting them in memory.\n",
"Since storage is cheap, you could create your own ListProperty based indexfiles with key_names that reflect the sort criteria. \nclass album_pubyear_List(db.Model):\n words = db.StringListProperty()\n\nclass album_length_List(db.Model):\n words = db.StringListProperty()\n\nclass album_artist_List(db.Model):\n words = db.StringListProperty()\n\nclass Album(db.Model):\n blah...\n\n def save(self):\n super(Album, self).save()\n\n # you could do this at save time or batch it and do\n # it with a cronjob or taskqueue\n\n words = []\n\n for field in [\"title\", \"artist\", \"label\", \"genre\", ...]:\n words.append(\"%s:%s\" %(field, getattr(self, field)))\n\n word_records = []\n now = repr(time.time())\n word_records.append(album_pubyear_List(parent=self, key_name=\"%s_%s\" %(self.pubyear, now)), words=words)\n word_records.append(album_length_List(parent=self, key_name=\"%s_%s\" %(self.album_length, now)), words=words)\n word_records.append(album_artist_List(parent=self, key_name=\"%s_%s\" %(self.artist_name, now)), words=words)\n db.put(word_records)\n\nNow when it's time to search you create an appropriate WHERE clause and call the appropriate model\nwhere = \"WHERE words = \" + \"%s:%s\" %(field-a, value-a) + \" AND \" + \"%s:%s\" %(field-b, value-b) etc.\naModel = \"album_pubyear_List\" # or anyone of the other key_name sorted wordlist models\n\nindexes = db.GqlQuery(\"\"\"SELECT __key__ from %s %s\"\"\" %(aModel, where))\nkeys = [k.parent() for k in indexes[offset:numresults+1]] # +1 for pagination\nobject_list = db.get(keys) # returns a sorted by key_name list of Albums\n\n",
"As you say, you can't have an inequality condition on one field and an order by another (or inequalities on two fields, etc, etc). The workaround is simply to use the \"best\" inequality condition to get data in memory (where \"best\" means the one that's expected to yield the least data) and then further refine it and order it by Python code in your application.\nPython's list comprehensions (and other forms of loops &c), list's sort method and the sorted built-in function, the itertools module in the standard library, and so on, all help a lot to make these kinds of tasks quite simple to perform in Python itself.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"django_models",
"google_app_engine",
"model",
"python"
] |
stackoverflow_0001213959_django_models_google_app_engine_model_python.txt
|
Q:
Storing data and searching by metadata?
Let's say I have a set of data where each row is a pair of coordinates: (X, Y). Associated with each point I have arbitrary metadata, such as {color: yellow} or {age: 2 years}.
I'd like to be able to store the data and metadata in such a way that I can query the metadata (eg: [rows where {age: 2 years, color: yellow}]) and in return receive all of the matching coordinate rows.
There are no predefined metadata columns or values, nor will all coordinate rows necessarily have the same metadata columns. What would be the best way to store this data for the fastest access? Would it be possible using something such as Tokyo Cabinet (without Tokyo Tyrant) or SQLite, or is there a better option?
A:
Any relational database should be able to handle something like that (you'd basically just being doing a join between a couple of tables, one for the data and one for the metadata). SQLite should work fine.
Your first table would have the data itself with a unique IDs for each entry. Then your second table would have something like 3 working columns: metadata key, metadata value, and associated entry id.
Example data table:
ID Data
--------
1 (1,1)
2 (7,4)
3 (2,3)
Example metadata table:
ID Key Value
--------------------------
1 "color" yellow
1 "age" 3
2 "color" "blue"
2 "age" 2
3 "color" "blue"
3 "age" 4
3 "loc" "usa"
Then if you wanted to search for all data points with an age of at least 3, you'd use a query like this:
SELECT * from datatable WHERE datatable.ID = metadatatable.ID AND metadatatable.Key="age" AND metadatatable.Value >= 3
A:
Using @Dav's schema, a way to get " [all coordinate rows where age=2 and color=blue] " is (assuming (ID, Key, Value) is Unique in metadatatable, i.e., the latter has no entirely duplicate rows):
SELECT datatable.Data
FROM datatable
JOIN metatadatable AS m USING(ID)
WHERE (m.Key="age" AND m.Value=2)
OR (m.Key="color" AND m.Value="blue")
GROUP BY datatable.ID, datatable.Data
HAVING COUNT()=2
A:
Since the columns are neither predefined nor consistent across all rows you have to either go
with bigtable type implementations such as google appengine (exapndo models w/listproperty) or cassandra/hbase etc. (see http://en.wikipedia.org/wiki/BigTable)
For simple implementations using sqlite you could create a string field formatted as
f1 | f2 | metadata as string
x1 | y1 | cola:val-a1 colb:val-b1 colc:val-c1
x2 | y2 | cola:val-a2 colx:val-x2
and use SELECT * from table WHERE metadata like "%cola:val-a2%"
|
Storing data and searching by metadata?
|
Let's say I have a set of data where each row is a pair of coordinates: (X, Y). Associated with each point I have arbitrary metadata, such as {color: yellow} or {age: 2 years}.
I'd like to be able to store the data and metadata in such a way that I can query the metadata (eg: [rows where {age: 2 years, color: yellow}]) and in return receive all of the matching coordinate rows.
There are no predefined metadata columns or values, nor will all coordinate rows necessarily have the same metadata columns. What would be the best way to store this data for the fastest access? Would it be possible using something such as Tokyo Cabinet (without Tokyo Tyrant) or SQLite, or is there a better option?
|
[
"Any relational database should be able to handle something like that (you'd basically just being doing a join between a couple of tables, one for the data and one for the metadata). SQLite should work fine.\nYour first table would have the data itself with a unique IDs for each entry. Then your second table would have something like 3 working columns: metadata key, metadata value, and associated entry id.\nExample data table:\nID Data\n--------\n1 (1,1)\n2 (7,4)\n3 (2,3)\n\nExample metadata table:\nID Key Value\n--------------------------\n1 \"color\" yellow\n1 \"age\" 3\n2 \"color\" \"blue\"\n2 \"age\" 2\n3 \"color\" \"blue\"\n3 \"age\" 4\n3 \"loc\" \"usa\"\n\nThen if you wanted to search for all data points with an age of at least 3, you'd use a query like this:\nSELECT * from datatable WHERE datatable.ID = metadatatable.ID AND metadatatable.Key=\"age\" AND metadatatable.Value >= 3\n\n",
"Using @Dav's schema, a way to get \" [all coordinate rows where age=2 and color=blue] \" is (assuming (ID, Key, Value) is Unique in metadatatable, i.e., the latter has no entirely duplicate rows):\nSELECT datatable.Data \n FROM datatable\n JOIN metatadatable AS m USING(ID)\n WHERE (m.Key=\"age\" AND m.Value=2)\n OR (m.Key=\"color\" AND m.Value=\"blue\")\n GROUP BY datatable.ID, datatable.Data\n HAVING COUNT()=2\n\n",
"Since the columns are neither predefined nor consistent across all rows you have to either go\nwith bigtable type implementations such as google appengine (exapndo models w/listproperty) or cassandra/hbase etc. (see http://en.wikipedia.org/wiki/BigTable)\nFor simple implementations using sqlite you could create a string field formatted as \nf1 | f2 | metadata as string\nx1 | y1 | cola:val-a1 colb:val-b1 colc:val-c1\nx2 | y2 | cola:val-a2 colx:val-x2\n\nand use SELECT * from table WHERE metadata like \"%cola:val-a2%\"\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"metadata",
"python"
] |
stackoverflow_0001220440_metadata_python.txt
|
Q:
How to make authkit session cookie HttpOnly in pylons?
I use authkit module with Pylons and I see that session cookie it sets (aptly named authkit) is not set to be HttpOnly.
Is there a simple way to make it HttpOnly? (By "simple" I mean the one that does not involve hacking authkit's code.)
A:
This is not documented in authkit, because it only started working in Python 2.6 (see here), but if you do have Python 2.6 then
authkit.cookie.params.httponly = true
in the config should work and do what you desire.
authkit internally uses a Cookie.SimpleCookie, and that's what limits the keys you can have for the authkit.cookie.params. -- up to Python 2.5 they were only the keys supported by the standard, RFC 2109, but in Python 2.6 the useful httponly extension was added -- which is how authkit gained support for it automatically... because, quite properly, it doesn't do its own checks but rather delegates all checks to SimpleCookie.
If you're stuck with Python 2.5 or earlier, then to make this work will require a little more effort (not changing authkit, but monkeypatching Python's Cookie.py, or better, if feasible, installing a newer version of Cookie.py from the Python 2.6 sources in a directory that's earlier in sys.path than the directory for Python's own standard library).
|
How to make authkit session cookie HttpOnly in pylons?
|
I use authkit module with Pylons and I see that session cookie it sets (aptly named authkit) is not set to be HttpOnly.
Is there a simple way to make it HttpOnly? (By "simple" I mean the one that does not involve hacking authkit's code.)
|
[
"This is not documented in authkit, because it only started working in Python 2.6 (see here), but if you do have Python 2.6 then \nauthkit.cookie.params.httponly = true\n\nin the config should work and do what you desire.\nauthkit internally uses a Cookie.SimpleCookie, and that's what limits the keys you can have for the authkit.cookie.params. -- up to Python 2.5 they were only the keys supported by the standard, RFC 2109, but in Python 2.6 the useful httponly extension was added -- which is how authkit gained support for it automatically... because, quite properly, it doesn't do its own checks but rather delegates all checks to SimpleCookie.\nIf you're stuck with Python 2.5 or earlier, then to make this work will require a little more effort (not changing authkit, but monkeypatching Python's Cookie.py, or better, if feasible, installing a newer version of Cookie.py from the Python 2.6 sources in a directory that's earlier in sys.path than the directory for Python's own standard library).\n"
] |
[
2
] |
[] |
[] |
[
"authkit",
"cookies",
"pylons",
"python"
] |
stackoverflow_0001220555_authkit_cookies_pylons_python.txt
|
Q:
Creating Date Intervals in Python
I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output.
So, how can I change this:
sum = 0
for i in range(1,11):
print sum
sum += i
To this?
InputDate = '2009-01-01'
for i in range('2009-01-01','2009-07-01'):
print InputDate
InputDate += i
I realize there is something in rrule that does this exact function:
a = date(2009, 1, 1)
b = date(2009, 7, 1)
for dt in rrule(DAILY, dtstart=a, until=b):
print dt.strftime("%Y-%m-%d")
But, I am restricted to older version of python.
This is the shell script version of what I am trying to do, if this helps clarify:
while [InputDate <= EndDate]
do
sql="SELECT Date,SUM(CostUsd) FROM DailyStats WHERE Date = '$InputDate' GROUP BY Date"
name=$(mysql -h -sN -u -p -e "$sql" > DateLoop-$InputDate.txt db)
echo "$name"
InputDate=$(( InputDate + 1 ))
done
So how can I do this in Python?
Adding follow up question here for readability. Unfortunately I can not use standard MySQL library as we have a proprietary setup with numerous instances running in parallel. The only way to run this type of query is to connect to one instance at a time, on the command line.
while day <= b:
print "Running extract for :" day
sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
os.system('mysql -h -sN -u -p -e " + sql + " > DateLoop-" + day + ".txt db')
day += one_day
A:
This will work:
import datetime
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 7, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
# do important stuff
day += one_day
A:
Try this:
import datetime
dt1 = datetime.date(2009, 1, 1)
dt2 = datetime.date(2009, 7, 1)
dt = dt1
while dt <= dt2:
print dt.strftime("%Y-%m-%d")
dt += datetime.timedelta(days=1)
You say you are restricted to an older version of Python. If you don't have the datetime module (Python < 2.3), then you can also do:
import time
dt1 = time.mktime(time.strptime('2009-01-01', '%Y-%m-%d'))
dt2 = time.mktime(time.strptime('2009-07-01', '%Y-%m-%d'))
ONE_DAY = 86400
dt = dt1
while dt <= dt2:
print time.strftime('%Y-%m-%d', time.gmtime(dt))
dt += ONE_DAY
A:
In [1]: from dateutil.relativedelta import *
In [2]: from datetime import *
In [3]: aday = datetime.today()
In [4]: nextweek = aday+relativedelta(weeks=1)
In [5]: while aday<nextweek:
...: print datetime.strftime(aday,format='%Y-%b-%d')
...: aday+=relativedelta(days=1)
...:
...:
#Output
2009-Aug-03
2009-Aug-04
2009-Aug-05
2009-Aug-06
2009-Aug-07
2009-Aug-08
2009-Aug-09
While you can do, most of the stuff about datetime using the stdlib, (IMO) dateutil lets you do it faster and better.
|
Creating Date Intervals in Python
|
I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output.
So, how can I change this:
sum = 0
for i in range(1,11):
print sum
sum += i
To this?
InputDate = '2009-01-01'
for i in range('2009-01-01','2009-07-01'):
print InputDate
InputDate += i
I realize there is something in rrule that does this exact function:
a = date(2009, 1, 1)
b = date(2009, 7, 1)
for dt in rrule(DAILY, dtstart=a, until=b):
print dt.strftime("%Y-%m-%d")
But, I am restricted to older version of python.
This is the shell script version of what I am trying to do, if this helps clarify:
while [InputDate <= EndDate]
do
sql="SELECT Date,SUM(CostUsd) FROM DailyStats WHERE Date = '$InputDate' GROUP BY Date"
name=$(mysql -h -sN -u -p -e "$sql" > DateLoop-$InputDate.txt db)
echo "$name"
InputDate=$(( InputDate + 1 ))
done
So how can I do this in Python?
Adding follow up question here for readability. Unfortunately I can not use standard MySQL library as we have a proprietary setup with numerous instances running in parallel. The only way to run this type of query is to connect to one instance at a time, on the command line.
while day <= b:
print "Running extract for :" day
sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
os.system('mysql -h -sN -u -p -e " + sql + " > DateLoop-" + day + ".txt db')
day += one_day
|
[
"This will work:\nimport datetime\n\na = datetime.date(2009, 1, 1)\nb = datetime.date(2009, 7, 1)\none_day = datetime.timedelta(1)\n\nday = a\n\nwhile day <= b:\n # do important stuff\n day += one_day\n\n",
"Try this:\nimport datetime\ndt1 = datetime.date(2009, 1, 1)\ndt2 = datetime.date(2009, 7, 1)\ndt = dt1\nwhile dt <= dt2:\n print dt.strftime(\"%Y-%m-%d\")\n dt += datetime.timedelta(days=1)\n\nYou say you are restricted to an older version of Python. If you don't have the datetime module (Python < 2.3), then you can also do:\nimport time\ndt1 = time.mktime(time.strptime('2009-01-01', '%Y-%m-%d'))\ndt2 = time.mktime(time.strptime('2009-07-01', '%Y-%m-%d'))\nONE_DAY = 86400\ndt = dt1\nwhile dt <= dt2:\n print time.strftime('%Y-%m-%d', time.gmtime(dt))\n dt += ONE_DAY\n\n",
"In [1]: from dateutil.relativedelta import *\n\nIn [2]: from datetime import *\n\nIn [3]: aday = datetime.today()\n\nIn [4]: nextweek = aday+relativedelta(weeks=1)\n\nIn [5]: while aday<nextweek:\n ...: print datetime.strftime(aday,format='%Y-%b-%d')\n ...: aday+=relativedelta(days=1)\n ...: \n ...: \n #Output\n2009-Aug-03\n2009-Aug-04\n2009-Aug-05\n2009-Aug-06\n2009-Aug-07\n2009-Aug-08\n2009-Aug-09\n\nWhile you can do, most of the stuff about datetime using the stdlib, (IMO) dateutil lets you do it faster and better.\n"
] |
[
7,
2,
2
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0001220872_mysql_python.txt
|
Q:
returning a value to a c# program through python script
I have a C# program which executes a python scrip
How can I retrieve the python returning value in my C# program ?
thanks!
A:
As far as I know, you should use ScriptScope object which you create from the ScriptEngine object using CreateScope method
ScriptEngine engine = ScriptRuntime.Create().GetEngine("py");
ScriptScope scope = engine.CreateScope();
Then you can share variables between the C# program and the python script by doing this
scope.SetVariable("x", x);
A:
if your using System.Diagnostics.Process to launch your python script, then you can get the return code after process exit
using
process.ExitCode
|
returning a value to a c# program through python script
|
I have a C# program which executes a python scrip
How can I retrieve the python returning value in my C# program ?
thanks!
|
[
"As far as I know, you should use ScriptScope object which you create from the ScriptEngine object using CreateScope method\nScriptEngine engine = ScriptRuntime.Create().GetEngine(\"py\");\nScriptScope scope = engine.CreateScope();\n\nThen you can share variables between the C# program and the python script by doing this\nscope.SetVariable(\"x\", x);\n\n",
"if your using System.Diagnostics.Process to launch your python script, then you can get the return code after process exit\nusing \nprocess.ExitCode\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"c#",
"python"
] |
stackoverflow_0001221135_c#_python.txt
|
Q:
java and python equivalent of php's foreach($array as $key => $value)
In php, one can handle a list of state names and their abbreviations with an associative array like this:
<?php
$stateArray = array(
"ALABAMA"=>"AL",
"ALASKA"=>"AK",
// etc...
"WYOMING"=>"WY"
);
foreach ($stateArray as $stateName => $stateAbbreviation){
print "The abbreviation for $stateName is $stateAbbreviation.\n\n";
}
?>
Output (with key order preserved):
The abbreviation for ALABAMA is AL.
The abbreviation for ALASKA is AK.
The abbreviation for WYOMING is WY.
EDIT: Note that the order of array elements is preserved in the output of the php version. The Java implementation, using a HashMap, does not guarantee the order of elements. Nor does the dictionary in Python.
How is this done in java and python? I only find approaches that supply the value, given the key, like python's:
stateDict = {
"ALASKA": "AK",
"WYOMING": "WY",
}
for key in stateDict:
value = stateDict[key]
EDIT: based on the answers, this was my solution in python,
# a list of two-tuples
stateList = [
('ALABAMA', 'AL'),
('ALASKA', 'AK'),
('WISCONSIN', 'WI'),
('WYOMING', 'WY'),
]
for name, abbreviation in stateList:
print name, abbreviation
Output:
ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY
Which is exactly what was required.
A:
in Python:
for key, value in stateDict.items(): # .iteritems() in Python 2.x
print "The abbreviation for %s is %s." % (key, value)
in Java:
Map<String,String> stateDict;
for (Map.Entry<String,String> e : stateDict.entrySet())
System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");
A:
in java for associative array use Map
import java.util.*;
class Foo
{
public static void main(String[] args)
{
Map<String, String> stateMap = new HashMap<String, String>();
stateMap.put("ALABAMA", "AL");
stateMap.put("ALASKA", "AK");
// ...
stateMap.put("WYOMING", "WY");
for (Map.Entry<String, String> state : stateMap.entrySet()) {
System.out.printf(
"The abbreviation for %s is %s%n",
state.getKey(),
state.getValue()
);
}
}
}
A:
Also, to maintain insertion order, you can use a LinkedHashMap instead of a HashMap.
A:
In python an ordered dictionary is available in Python 2.7 (not yet released) and Python 3.1. It's called OrderedDict.
A:
This is the modified code from o948 where you use a TreeMap instead of a HashMap. The Tree map will preserve the ordering of the keys by the key.
import java.util.*;
class Foo
{
public static void main(String[] args)
{
Map<String, String> stateMap = new TreeMap<String, String>();
stateMap.put("ALABAMA", "AL");
stateMap.put("ALASKA", "AK");
// ...
stateMap.put("WYOMING", "WY");
for (Map.Entry<String, String> state : stateMap.entrySet()) {
System.out.printf(
"The abbreviation for %s is %s%n",
state.getKey(),
state.getValue()
);
}
}
}
A:
Another way of doing it in Java. Although a better way has already been posted, this one's syntactically closer to your php code.
for (String x:stateDict.keySet()){
System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
}
A:
Along the lines of Alexander's answer...
The native python dictionary doesn't maintain ordering for maximum efficiency of its primary use: an unordered mapping of keys to values.
I can think of two workarounds:
look at the source code of OrderedDict and include it in your own program.
make a list that holds the keys in order:
states = ['Alabamba', 'Alaska', ...]
statesd = {'Alabamba':'AL', 'Alaska':'AK', ...}
for k in states:
print "The abbreviation for %s is %s." % (k, statesd[k])
A:
TreeMap is not an answer to your question because it sorts elements by key, while LinkedHashMap preserves original order. However, TreeMap is more suitable for the dictionary because of sorting.
|
java and python equivalent of php's foreach($array as $key => $value)
|
In php, one can handle a list of state names and their abbreviations with an associative array like this:
<?php
$stateArray = array(
"ALABAMA"=>"AL",
"ALASKA"=>"AK",
// etc...
"WYOMING"=>"WY"
);
foreach ($stateArray as $stateName => $stateAbbreviation){
print "The abbreviation for $stateName is $stateAbbreviation.\n\n";
}
?>
Output (with key order preserved):
The abbreviation for ALABAMA is AL.
The abbreviation for ALASKA is AK.
The abbreviation for WYOMING is WY.
EDIT: Note that the order of array elements is preserved in the output of the php version. The Java implementation, using a HashMap, does not guarantee the order of elements. Nor does the dictionary in Python.
How is this done in java and python? I only find approaches that supply the value, given the key, like python's:
stateDict = {
"ALASKA": "AK",
"WYOMING": "WY",
}
for key in stateDict:
value = stateDict[key]
EDIT: based on the answers, this was my solution in python,
# a list of two-tuples
stateList = [
('ALABAMA', 'AL'),
('ALASKA', 'AK'),
('WISCONSIN', 'WI'),
('WYOMING', 'WY'),
]
for name, abbreviation in stateList:
print name, abbreviation
Output:
ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY
Which is exactly what was required.
|
[
"in Python:\nfor key, value in stateDict.items(): # .iteritems() in Python 2.x\n print \"The abbreviation for %s is %s.\" % (key, value)\n\nin Java:\nMap<String,String> stateDict;\n\nfor (Map.Entry<String,String> e : stateDict.entrySet())\n System.out.println(\"The abbreviation for \" + e.getKey() + \" is \" + e.getValue() + \".\");\n\n",
"in java for associative array use Map\nimport java.util.*;\n\nclass Foo\n{\n public static void main(String[] args)\n {\n Map<String, String> stateMap = new HashMap<String, String>();\n stateMap.put(\"ALABAMA\", \"AL\");\n stateMap.put(\"ALASKA\", \"AK\");\n // ...\n stateMap.put(\"WYOMING\", \"WY\");\n\n for (Map.Entry<String, String> state : stateMap.entrySet()) {\n System.out.printf(\n \"The abbreviation for %s is %s%n\",\n state.getKey(),\n state.getValue()\n );\n }\n }\n}\n\n",
"Also, to maintain insertion order, you can use a LinkedHashMap instead of a HashMap.\n",
"In python an ordered dictionary is available in Python 2.7 (not yet released) and Python 3.1. It's called OrderedDict.\n",
"This is the modified code from o948 where you use a TreeMap instead of a HashMap. The Tree map will preserve the ordering of the keys by the key.\nimport java.util.*;\n\nclass Foo\n{\n public static void main(String[] args)\n {\n Map<String, String> stateMap = new TreeMap<String, String>();\n stateMap.put(\"ALABAMA\", \"AL\");\n stateMap.put(\"ALASKA\", \"AK\");\n // ...\n stateMap.put(\"WYOMING\", \"WY\");\n\n for (Map.Entry<String, String> state : stateMap.entrySet()) {\n System.out.printf(\n \"The abbreviation for %s is %s%n\",\n state.getKey(),\n state.getValue()\n );\n }\n }\n }\n\n",
"Another way of doing it in Java. Although a better way has already been posted, this one's syntactically closer to your php code.\nfor (String x:stateDict.keySet()){\n System.out.printf(\"The abbreviation for %s is %s\\n\",x,stateDict.get(x));\n }\n\n",
"Along the lines of Alexander's answer...\nThe native python dictionary doesn't maintain ordering for maximum efficiency of its primary use: an unordered mapping of keys to values.\nI can think of two workarounds:\n\nlook at the source code of OrderedDict and include it in your own program.\nmake a list that holds the keys in order:\nstates = ['Alabamba', 'Alaska', ...] \nstatesd = {'Alabamba':'AL', 'Alaska':'AK', ...}\nfor k in states:\n print \"The abbreviation for %s is %s.\" % (k, statesd[k])\n\n\n",
"TreeMap is not an answer to your question because it sorts elements by key, while LinkedHashMap preserves original order. However, TreeMap is more suitable for the dictionary because of sorting.\n"
] |
[
34,
6,
2,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"associative_array",
"java",
"php",
"python"
] |
stackoverflow_0001219548_associative_array_java_php_python.txt
|
Q:
Need to get the rest of an iterator in python
Say I have an iterator.
After iterating over a few items of the iterator, I will have to get rid of these first few items and return an iterator(preferably the same) with the rest of the items. How do I go about?
Also, Do iterators support remove or pop operations (like lists)?
A:
Yes, just use iter.next()
Example
iter = xrange(3).__iter__()
iter.next() # this pops 0
for i in iter:
print i
1
2
You can pop off the front of an iterator with .next(). You cannot do any other fancy operations.
A:
The itertools.dropwhile() function might be helpful, too:
dropwhile(lambda x: x<5, xrange(10))
|
Need to get the rest of an iterator in python
|
Say I have an iterator.
After iterating over a few items of the iterator, I will have to get rid of these first few items and return an iterator(preferably the same) with the rest of the items. How do I go about?
Also, Do iterators support remove or pop operations (like lists)?
|
[
"Yes, just use iter.next()\nExample\niter = xrange(3).__iter__()\n\niter.next() # this pops 0\n\nfor i in iter:\n print i\n\n1\n2\n\nYou can pop off the front of an iterator with .next(). You cannot do any other fancy operations.\n",
"The itertools.dropwhile() function might be helpful, too:\ndropwhile(lambda x: x<5, xrange(10))\n\n"
] |
[
7,
7
] |
[] |
[] |
[
"iterator",
"python"
] |
stackoverflow_0001220640_iterator_python.txt
|
Q:
need to put a nested Dict into a text file
I have a nested dict like this
d={ time1 : column1 : {data1,data2,data3}
column2 : {data1,data2,data3}
column3 : {data1,data2,data3} #So on.
time2 : {column1: } #Same as Above
}
data1,data2,data3 represent the type of data and not the data itself
I need to put this dict into a file like this.
Timestamp col1/data1 Col1/data2 col1/data3 col2/data1 col2/data2 col2/data3 (So on...)
My problem is How do I ensure that the text goes under the corresponding column?
i.e Say I have put some text under time1 column14 and I again come across column14 in another timestamp. How do I keep track of the location of these columns in the text file?
The columns are just numbers (in string form)
A:
I would use JSON.
In Python 2.6 it's directly available, in earlier Python's you have to download and install it.
try:
import json
exception ImportError:
import simplejson as json
out= open( "myFile.json", "w" )
json.dump( { 'timestamp': time.time(), 'data': d }, indent=2 )
out.close()
Works nicely. Easy to edit manually. Easy to parse.
A:
I would do it like this:
#get the row with maximum number of columns
maxrowlen = 0
maxrowkey = ""
for timesid in d.keys():
if len(timesid.keys()) > maxrowlen:
maxrowlen = len(timesid.keys())
maxrowkey = timesid
maxrowcols = sorted(d[maxrowkey].keys())
# prepare the writing
cell_format = "%10r" # or whatever suits your data
# create the output string
lines = []
for timesid in d.keys(): # go through all times
line = ""
for col in maxrowcols: # go through the standard columns
colstr = ""
if col in d[timesid].keys(): # create an entry for each standard column
colstr += cell_format % d[timesid][col] # either from actual data
else:
colstr += cell_format % "" # or blanks
line += colstr
lines.append(line)
text = "\n".join(lines)
|
need to put a nested Dict into a text file
|
I have a nested dict like this
d={ time1 : column1 : {data1,data2,data3}
column2 : {data1,data2,data3}
column3 : {data1,data2,data3} #So on.
time2 : {column1: } #Same as Above
}
data1,data2,data3 represent the type of data and not the data itself
I need to put this dict into a file like this.
Timestamp col1/data1 Col1/data2 col1/data3 col2/data1 col2/data2 col2/data3 (So on...)
My problem is How do I ensure that the text goes under the corresponding column?
i.e Say I have put some text under time1 column14 and I again come across column14 in another timestamp. How do I keep track of the location of these columns in the text file?
The columns are just numbers (in string form)
|
[
"I would use JSON.\nIn Python 2.6 it's directly available, in earlier Python's you have to download and install it.\ntry:\n import json\nexception ImportError:\n import simplejson as json\n\nout= open( \"myFile.json\", \"w\" )\njson.dump( { 'timestamp': time.time(), 'data': d }, indent=2 )\nout.close()\n\nWorks nicely. Easy to edit manually. Easy to parse.\n",
"I would do it like this:\n#get the row with maximum number of columns\nmaxrowlen = 0\nmaxrowkey = \"\"\nfor timesid in d.keys():\n if len(timesid.keys()) > maxrowlen:\n maxrowlen = len(timesid.keys())\n maxrowkey = timesid\nmaxrowcols = sorted(d[maxrowkey].keys())\n\n# prepare the writing\ncell_format = \"%10r\" # or whatever suits your data\n\n# create the output string\nlines = []\nfor timesid in d.keys(): # go through all times\n line = \"\"\n for col in maxrowcols: # go through the standard columns\n colstr = \"\"\n if col in d[timesid].keys(): # create an entry for each standard column\n colstr += cell_format % d[timesid][col] # either from actual data\n else:\n colstr += cell_format % \"\" # or blanks\n line += colstr\n lines.append(line)\n\ntext = \"\\n\".join(lines)\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"dictionary",
"file",
"python"
] |
stackoverflow_0001221202_dictionary_file_python.txt
|
Q:
Find unique elements in tuples in a python list
Is there a better way to do this in python, or rather: Is this a good way to do it?
x = ('a', 'b', 'c')
y = ('d', 'e', 'f')
z = ('g', 'e', 'i')
l = [x, y, z]
s = set([e for (_, e, _) in l])
I looks somewhat ugly but does what i need without writing a complex "get_unique_elements_from_tuple_list" function... ;)
edit: expected value of s is set(['b','e'])
A:
That's fine, that's what sets are for. One thing I would change is this:
s = set(e[1] for e in l)
as it enhances readability. Note that I also turned the list comprehension into a generator expression; no need to create a temporary list.
|
Find unique elements in tuples in a python list
|
Is there a better way to do this in python, or rather: Is this a good way to do it?
x = ('a', 'b', 'c')
y = ('d', 'e', 'f')
z = ('g', 'e', 'i')
l = [x, y, z]
s = set([e for (_, e, _) in l])
I looks somewhat ugly but does what i need without writing a complex "get_unique_elements_from_tuple_list" function... ;)
edit: expected value of s is set(['b','e'])
|
[
"That's fine, that's what sets are for. One thing I would change is this:\ns = set(e[1] for e in l)\n\nas it enhances readability. Note that I also turned the list comprehension into a generator expression; no need to create a temporary list.\n"
] |
[
24
] |
[] |
[] |
[
"list",
"python",
"set",
"tuples"
] |
stackoverflow_0001221775_list_python_set_tuples.txt
|
Q:
Screen Scrape Form Results
I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine they could use it as they wanted to.
My question: is it even possible to perform screen scraping on the response to a form submission to another site? If so, what are the gotchas that I should look out for. Obvious legal/ethical issues aside since they already asked for permission to do what we're planning to do.
As an aside, I would prefer to do any processing in python.
Thanks
A:
A really nice library for screen-scraping is mechanize, which I believe is a clone of an original library written in Perl. Anyway, that in combination with the ClientForm module, and some additional help from either BeautifulSoup and you should be away.
I've written loads of screen-scraping code in Python and these modules turned out to be the most useful. Most of the stuff that mechanize does could in theory be done by simply using the urllib2 or httplib modules from the standard library, but mechanize makes this stuff a breeze: essentially it gives you a programmatic browser (note, it does not require a browser to work, but mearly provides you with an API that behaves like a completely customisable browser).
For post-processing, I've had a lot of success with BeautifulSoup, but lxml.html is a good choice too.
Basically, you will be able to do this in Python for sure, and your results should be really good with the range of tools out there.
A:
You can pass a data parameter to urllib.urlopen to send POST data with the request just like you had filled out the form. You'll obviously have to take a look at what data exactly the form contains.
Also, if the form has method="GET", the request data is just part of the url given to urlopen.
Pretty much standard for scraping the returned HTML data is BeautifulSoup.
A:
I see the other two answers already mention all the major libraries of choice for the purpose... as long as the site being scraped does not make extensive use of Javascript, that is. If it IS a Javascript-heavy site and dependent on JS for the data it fetches and display (e.g. via AJAX) your problem is an order of magnitude harder; in that case, I might suggest starting with crowbar, some customization of diggstripper, or selenium, etc.
You'll have to do substantial work in Javascript and probably dedicated work to deal with the specifics of the (hypothetically JS-heavy) site in question, depending on the JS frameworks it uses, etc; that's why the job is so much harder if that is the case. But in any case you might end up with (at least in part) local HTML copies of the site's pages as displayed, and end by scraping those copies with the other tools already recommended. Good luck: may the sites you scrape always be Javascript-light!-)
A:
Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
Ian Blicking agrees.
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.
|
Screen Scrape Form Results
|
I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine they could use it as they wanted to.
My question: is it even possible to perform screen scraping on the response to a form submission to another site? If so, what are the gotchas that I should look out for. Obvious legal/ethical issues aside since they already asked for permission to do what we're planning to do.
As an aside, I would prefer to do any processing in python.
Thanks
|
[
"A really nice library for screen-scraping is mechanize, which I believe is a clone of an original library written in Perl. Anyway, that in combination with the ClientForm module, and some additional help from either BeautifulSoup and you should be away.\nI've written loads of screen-scraping code in Python and these modules turned out to be the most useful. Most of the stuff that mechanize does could in theory be done by simply using the urllib2 or httplib modules from the standard library, but mechanize makes this stuff a breeze: essentially it gives you a programmatic browser (note, it does not require a browser to work, but mearly provides you with an API that behaves like a completely customisable browser).\nFor post-processing, I've had a lot of success with BeautifulSoup, but lxml.html is a good choice too.\nBasically, you will be able to do this in Python for sure, and your results should be really good with the range of tools out there.\n",
"You can pass a data parameter to urllib.urlopen to send POST data with the request just like you had filled out the form. You'll obviously have to take a look at what data exactly the form contains.\nAlso, if the form has method=\"GET\", the request data is just part of the url given to urlopen.\nPretty much standard for scraping the returned HTML data is BeautifulSoup.\n",
"I see the other two answers already mention all the major libraries of choice for the purpose... as long as the site being scraped does not make extensive use of Javascript, that is. If it IS a Javascript-heavy site and dependent on JS for the data it fetches and display (e.g. via AJAX) your problem is an order of magnitude harder; in that case, I might suggest starting with crowbar, some customization of diggstripper, or selenium, etc.\nYou'll have to do substantial work in Javascript and probably dedicated work to deal with the specifics of the (hypothetically JS-heavy) site in question, depending on the JS frameworks it uses, etc; that's why the job is so much harder if that is the case. But in any case you might end up with (at least in part) local HTML copies of the site's pages as displayed, and end by scraping those copies with the other tools already recommended. Good luck: may the sites you scrape always be Javascript-light!-)\n",
"Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles \"broken\" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.\nIan Blicking agrees.\nThere's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.\n"
] |
[
5,
2,
0,
0
] |
[] |
[] |
[
"forms",
"python",
"screen_scraping"
] |
stackoverflow_0001222373_forms_python_screen_scraping.txt
|
Q:
Is there a good html parser like HtmlAgilityPack (.NET) for Python?
I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: http://www.codeplex.com/htmlagilitypack), but for using with Python.
Anyone knows?
A:
Use Beautiful Soup like everyone does.
A:
Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
Ian Blicking agrees.
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.
A:
Beautiful Soup should be something you search for. It is a html/xml parser that can deal with invalid pages and allows e.g. to iterate over specific tags.
|
Is there a good html parser like HtmlAgilityPack (.NET) for Python?
|
I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: http://www.codeplex.com/htmlagilitypack), but for using with Python.
Anyone knows?
|
[
"Use Beautiful Soup like everyone does.\n",
"Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles \"broken\" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.\nIan Blicking agrees.\nThere's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.\n",
"Beautiful Soup should be something you search for. It is a html/xml parser that can deal with invalid pages and allows e.g. to iterate over specific tags.\n"
] |
[
8,
8,
0
] |
[] |
[] |
[
"html",
"parsing",
"python"
] |
stackoverflow_0001222222_html_parsing_python.txt
|
Q:
URL tree walker in Python?
For URLs that show file trees, such as Pypi packages,
is there a small solid module to walk the URL tree and list it like ls -lR?
I gather (correct me) that there's no standard encoding of file attributes,
link types, size, date ... in html <A attributes
so building a solid URLtree module on shifting sands is tough.
But surely this wheel (Unix file tree -> html -> treewalk API -> ls -lR or find)
has been done?
(There seem to be several spiders / web crawlers / scrapers out there, but they look ugly and ad hoc so far, despite BeautifulSoup for parsing).
A:
Apache servers are very common, and they have a relatively standard way of listing file directories.
Here's a simple enough script that does what you want, you should be able to make it do what you want.
Usage: python list_apache_dir.py
import sys
import urllib
import re
parse_re = re.compile('href="([^"]*)".*(..-...-.... ..:..).*?(\d+[^\s<]*|-)')
# look for a link + a timestamp + a size ('-' for dir)
def list_apache_dir(url):
try:
html = urllib.urlopen(url).read()
except IOError, e:
print 'error fetching %s: %s' % (url, e)
return
if not url.endswith('/'):
url += '/'
files = parse_re.findall(html)
dirs = []
print url + ' :'
print '%4d file' % len(files) + 's' * (len(files) != 1)
for name, date, size in files:
if size.strip() == '-':
size = 'dir'
if name.endswith('/'):
dirs += [name]
print '%5s %s %s' % (size, date, name)
for dir in dirs:
print
list_apache_dir(url + dir)
for url in sys.argv[1:]:
print
list_apache_dir(url)
A:
Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
Ian Blicking agrees.
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.
It has CSS selectors as well so this sort of thing is trivial.
A:
Turns out that BeautifulSoup one-liners like these can turn <table> rows into Python --
from BeautifulSoup import BeautifulSoup
def trow_cols( trow ):
""" soup.table( "tr" ) -> <td> strings like
[None, u'Name', u'Last modified', u'Size', u'Description']
"""
return [td.next.string for td in trow( "td" )]
def trow_headers( trow ):
""" soup.table( "tr" ) -> <th> table header strings like
[None, u'Achoo-1.0-py2.5.egg', u'11-Aug-2008 07:40 ', u'8.9K']
"""
return [th.next.string for th in trow( "th" )]
if __name__ == "__main__":
...
soup = BeautifulSoup( html )
if soup.table:
trows = soup.table( "tr" )
print "headers:", trow_headers( trows[0] )
for row in trows[1:]:
print trow_cols( row )
Compared to sysrqb's one-line regexp above, this is ... longer;
who said
"You can parse some of the html all of
the time, or all of the html some of
the time, but not ..."
|
URL tree walker in Python?
|
For URLs that show file trees, such as Pypi packages,
is there a small solid module to walk the URL tree and list it like ls -lR?
I gather (correct me) that there's no standard encoding of file attributes,
link types, size, date ... in html <A attributes
so building a solid URLtree module on shifting sands is tough.
But surely this wheel (Unix file tree -> html -> treewalk API -> ls -lR or find)
has been done?
(There seem to be several spiders / web crawlers / scrapers out there, but they look ugly and ad hoc so far, despite BeautifulSoup for parsing).
|
[
"Apache servers are very common, and they have a relatively standard way of listing file directories.\nHere's a simple enough script that does what you want, you should be able to make it do what you want.\nUsage: python list_apache_dir.py \nimport sys\nimport urllib\nimport re\n\nparse_re = re.compile('href=\"([^\"]*)\".*(..-...-.... ..:..).*?(\\d+[^\\s<]*|-)')\n # look for a link + a timestamp + a size ('-' for dir)\ndef list_apache_dir(url):\n try:\n html = urllib.urlopen(url).read()\n except IOError, e:\n print 'error fetching %s: %s' % (url, e)\n return\n if not url.endswith('/'):\n url += '/'\n files = parse_re.findall(html)\n dirs = []\n print url + ' :' \n print '%4d file' % len(files) + 's' * (len(files) != 1)\n for name, date, size in files:\n if size.strip() == '-':\n size = 'dir'\n if name.endswith('/'):\n dirs += [name]\n print '%5s %s %s' % (size, date, name)\n\n for dir in dirs:\n print\n list_apache_dir(url + dir)\n\nfor url in sys.argv[1:]:\n print\n list_apache_dir(url) \n\n",
"Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.\nIan Blicking agrees.\nThere's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.\nIt has CSS selectors as well so this sort of thing is trivial.\n",
"Turns out that BeautifulSoup one-liners like these can turn <table> rows into Python --\nfrom BeautifulSoup import BeautifulSoup\n\ndef trow_cols( trow ):\n \"\"\" soup.table( \"tr\" ) -> <td> strings like\n [None, u'Name', u'Last modified', u'Size', u'Description'] \n \"\"\" \n return [td.next.string for td in trow( \"td\" )]\n\ndef trow_headers( trow ):\n \"\"\" soup.table( \"tr\" ) -> <th> table header strings like\n [None, u'Achoo-1.0-py2.5.egg', u'11-Aug-2008 07:40 ', u'8.9K'] \n \"\"\" \n return [th.next.string for th in trow( \"th\" )]\n\nif __name__ == \"__main__\":\n ...\n soup = BeautifulSoup( html )\n if soup.table:\n trows = soup.table( \"tr\" )\n print \"headers:\", trow_headers( trows[0] )\n for row in trows[1:]:\n print trow_cols( row )\n\nCompared to sysrqb's one-line regexp above, this is ... longer;\nwho said\n\n\"You can parse some of the html all of\n the time, or all of the html some of\n the time, but not ...\"\n\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"beautifulsoup",
"directory_walk",
"python",
"tree"
] |
stackoverflow_0000686147_beautifulsoup_directory_walk_python_tree.txt
|
Q:
Is there a way to modify a class in a class method in Python?
I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get:
NameError: global name 'ClassName' is not defined
Is there a way for a class method to modify the class? Something like this but that actually works:
class ClassName(object):
def HocusPocus(name):
setattr(ClassName, name, name)
HocusPocus("blah")
HocusPocus("bleh")
A:
Class methods get the class passed as the first argument:
class Bla(object):
@classmethod
def cm(cls,value):
cls.storedValue = value
Bla.cm("Hello")
print Bla.storedValue # prints "Hello"
Edit: I think I understand your problem now. If I get it correctly, all you want to do is this:
class Bla(object):
storedValue = "Hello again"
print Bla.storedValue # prints "Hello again"
Class creation in Python (pretty much) simply means:
Create a fresh namespace.
Run the code that you find inside the class body using this namespace
Put everything that's left in the namespace into the class as class attributes.
Since storedValue is in the namespace after step 2, it's turned into a class attribute in step 3.
A:
Another way you could do this would be to use a class decorator, though these are only available from Python 2.6 onwards IIRC.
Something like this:
def addattributes(cls):
cls.foobar = 10
return cls
@addattributes
class MyClass(object):
pass
print MyClass.foobar
This kind of this most useful when you want to "decorate" a number of classes with some specific functionality / properties. In your case, if you only want to do this once, you might just want to use class methods as previously shown.
A:
While many good suggestions have been advanced, the closest one can get to the originally requested code, that is:
class ClassName(object):
def HocusPocus(name):
setattr(ClassName, name, property(fget=..., fset=...))
HocusPocus("blah")
HocusPocus("bleh")
is this:
class ClassName(object):
def HocusPocus(name):
return property(fget=..., fset=...)
blah = HocusPocus("blah")
bleh = HocusPocus("bleh")
I'm assuming the mysterious ... redacted parts need access to name too (otherwise it's not necessary to pass it as an argument).
The point is that, within the class body, HocusPocus is still just a function (since the class object doesn't exist yet until the class body finishes executing, the body is essentially like a function body that's running in its local dict [without the namespace optimizations typically performed by the Python compiler on locals of a real function, but that only makes the semantics simpler!]) and in particular it can be called within that body, can return a value, that value can be assigned (to a local variable of the class body, which will become a class attribute at the end of the body's execution), etc.
If you don't want ClassName.HocusPocus hanging around later, when you're done executing it within the class body just add a del statement (e.g. as the last statement in the class body):
del HocusPocus
|
Is there a way to modify a class in a class method in Python?
|
I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get:
NameError: global name 'ClassName' is not defined
Is there a way for a class method to modify the class? Something like this but that actually works:
class ClassName(object):
def HocusPocus(name):
setattr(ClassName, name, name)
HocusPocus("blah")
HocusPocus("bleh")
|
[
"Class methods get the class passed as the first argument:\nclass Bla(object):\n @classmethod\n def cm(cls,value):\n cls.storedValue = value\n\nBla.cm(\"Hello\")\n\nprint Bla.storedValue # prints \"Hello\"\n\n\nEdit: I think I understand your problem now. If I get it correctly, all you want to do is this:\nclass Bla(object):\n storedValue = \"Hello again\"\n\nprint Bla.storedValue # prints \"Hello again\"\n\nClass creation in Python (pretty much) simply means:\n\nCreate a fresh namespace.\nRun the code that you find inside the class body using this namespace\nPut everything that's left in the namespace into the class as class attributes.\n\nSince storedValue is in the namespace after step 2, it's turned into a class attribute in step 3.\n",
"Another way you could do this would be to use a class decorator, though these are only available from Python 2.6 onwards IIRC.\nSomething like this:\ndef addattributes(cls):\n cls.foobar = 10\n return cls\n\n@addattributes\nclass MyClass(object):\n pass\n\nprint MyClass.foobar\n\nThis kind of this most useful when you want to \"decorate\" a number of classes with some specific functionality / properties. In your case, if you only want to do this once, you might just want to use class methods as previously shown.\n",
"While many good suggestions have been advanced, the closest one can get to the originally requested code, that is:\nclass ClassName(object):\n def HocusPocus(name):\n setattr(ClassName, name, property(fget=..., fset=...))\n\n HocusPocus(\"blah\")\n HocusPocus(\"bleh\")\n\nis this:\nclass ClassName(object):\n\n def HocusPocus(name):\n return property(fget=..., fset=...)\n\n blah = HocusPocus(\"blah\")\n bleh = HocusPocus(\"bleh\")\n\nI'm assuming the mysterious ... redacted parts need access to name too (otherwise it's not necessary to pass it as an argument).\nThe point is that, within the class body, HocusPocus is still just a function (since the class object doesn't exist yet until the class body finishes executing, the body is essentially like a function body that's running in its local dict [without the namespace optimizations typically performed by the Python compiler on locals of a real function, but that only makes the semantics simpler!]) and in particular it can be called within that body, can return a value, that value can be assigned (to a local variable of the class body, which will become a class attribute at the end of the body's execution), etc.\nIf you don't want ClassName.HocusPocus hanging around later, when you're done executing it within the class body just add a del statement (e.g. as the last statement in the class body):\n del HocusPocus\n\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001222311_python.txt
|
Q:
BeautifulSoup 3.1 parser breaks far too easily
I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously.
Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borking on some nasty HTML I'm loading from a crabby website:
<HTML>
<HEAD>
<TITLE>Title</TITLE>
<HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</HEAD>
<BODY>
...
...
</BODY>
</HTML>
BeautifulSoup gives up after the <HTTP-EQUIV...> tag
In [1]: print BeautifulSoup(c).prettify()
<html>
<head>
<title>
Title
</title>
</head>
</html>
The problem is clearly the HTTP-EQUIV tag, which is really a very malformed <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> tag. Evidently, I need to specify this as self-closing, but no matter what I specify I can't fix it:
In [2]: print BeautifulSoup(c,selfClosingTags=['http-equiv',
'http-equiv="pragma"']).prettify()
<html>
<head>
<title>
Title
</title>
</head>
</html>
Is there a verbose debug mode in which BeautifulSoup will tell me what it is doing, so I can figure out what it is treating as the tag name in this case?
A:
Having problems with Beautiful Soup 3.1.0? recommends to use html5lib's parser as one of workarounds.
#!/usr/bin/env python
from html5lib import HTMLParser, treebuilders
parser = HTMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup"))
c = """<HTML>
<HEAD>
<TITLE>Title</TITLE>
<HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</HEAD>
<BODY>
...
...
</BODY>
</HTML>"""
soup = parser.parse(c)
print soup.prettify()
Output:
<html>
<head>
<title>
Title
</title>
</head>
<body>
<http-equiv="pragma" content="NO-CACHE">
...
...
</http-equiv="pragma">
</body>
</html>
The output shows that html5lib hasn't fixed the problem in this case though.
A:
Try lxml (and its html module). Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
Ian Blicking agrees.
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.
A:
Your problem must be something else; it works fine for me:
In [1]: import BeautifulSoup
In [2]: c = """<HTML>
...: <HEAD>
...: <TITLE>Title</TITLE>
...: <HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
...: </HEAD>
...: <BODY>
...: ...
...: ...
...: </BODY>
...: </HTML>
...: """
In [3]: print BeautifulSoup.BeautifulSoup(c).prettify()
<html>
<head>
<title>
Title
</title>
<http-equiv>
</http-equiv>
</head>
<body>
...
...
</body>
</html>
In [4]:
This is Python 2.5.2 with BeautifulSoup 3.0.7a — maybe it's different in older/newer versions? This is exactly the kind of soup BeautifulSoup handles so beautifully, so I doubt it's been changed at some point… Is there something else to the structure that you haven't mentioned in the problem?
|
BeautifulSoup 3.1 parser breaks far too easily
|
I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously.
Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borking on some nasty HTML I'm loading from a crabby website:
<HTML>
<HEAD>
<TITLE>Title</TITLE>
<HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</HEAD>
<BODY>
...
...
</BODY>
</HTML>
BeautifulSoup gives up after the <HTTP-EQUIV...> tag
In [1]: print BeautifulSoup(c).prettify()
<html>
<head>
<title>
Title
</title>
</head>
</html>
The problem is clearly the HTTP-EQUIV tag, which is really a very malformed <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> tag. Evidently, I need to specify this as self-closing, but no matter what I specify I can't fix it:
In [2]: print BeautifulSoup(c,selfClosingTags=['http-equiv',
'http-equiv="pragma"']).prettify()
<html>
<head>
<title>
Title
</title>
</head>
</html>
Is there a verbose debug mode in which BeautifulSoup will tell me what it is doing, so I can figure out what it is treating as the tag name in this case?
|
[
"Having problems with Beautiful Soup 3.1.0? recommends to use html5lib's parser as one of workarounds.\n#!/usr/bin/env python\nfrom html5lib import HTMLParser, treebuilders\n\nparser = HTMLParser(tree=treebuilders.getTreeBuilder(\"beautifulsoup\"))\n\nc = \"\"\"<HTML>\n <HEAD>\n <TITLE>Title</TITLE>\n <HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\">\n </HEAD>\n <BODY>\n ...\n ...\n </BODY>\n</HTML>\"\"\"\n\nsoup = parser.parse(c)\nprint soup.prettify()\n\nOutput:\n<html>\n <head>\n <title>\n Title\n </title>\n </head>\n <body>\n <http-equiv=\"pragma\" content=\"NO-CACHE\">\n ...\n ...\n </http-equiv=\"pragma\">\n </body>\n</html>\n\nThe output shows that html5lib hasn't fixed the problem in this case though.\n",
"Try lxml (and its html module). Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles \"broken\" HTML better than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.\nIan Blicking agrees.\nThere's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.\n",
"Your problem must be something else; it works fine for me: \nIn [1]: import BeautifulSoup\n\nIn [2]: c = \"\"\"<HTML>\n ...: <HEAD>\n ...: <TITLE>Title</TITLE>\n ...: <HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\">\n ...: </HEAD>\n ...: <BODY>\n ...: ...\n ...: ...\n ...: </BODY>\n ...: </HTML>\n ...: \"\"\"\n\nIn [3]: print BeautifulSoup.BeautifulSoup(c).prettify()\n<html>\n <head>\n <title>\n Title\n </title>\n <http-equiv>\n </http-equiv>\n </head>\n <body>\n ...\n ...\n </body>\n</html>\n\n\nIn [4]: \n\nThis is Python 2.5.2 with BeautifulSoup 3.0.7a — maybe it's different in older/newer versions? This is exactly the kind of soup BeautifulSoup handles so beautifully, so I doubt it's been changed at some point… Is there something else to the structure that you haven't mentioned in the problem?\n"
] |
[
6,
3,
2
] |
[] |
[] |
[
"beautifulsoup",
"html",
"parsing",
"python"
] |
stackoverflow_0000459552_beautifulsoup_html_parsing_python.txt
|
Q:
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string?
I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition.
For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers.
Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters.
Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now.
In response to some comments here is some more information:
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc').
A:
A Dynamic Programming solution (if I understood the question right):
def dynProgSolution(text, probs):
probUpTo = [1]
for i in range(1, len(text)+1):
cur = sum(v*probs[text[k:i]] for k, v in enumerate(probUpTo))
probUpTo.append(cur)
return probUpTo[-1]
print dynProgSolution(
'abc',
{'a': 0.1, 'b': 0.2, 'c': 0.3,
'ab': 0.4, 'bc': 0.5, 'abc': 0.6}
)
The complexity is O(N2) so it will easily solve the problem for N=20.
How why does this work:
Everything you will multiply by probs['a']*probs['b'] you will also multiply by probs['ab']
Thanks to the Distributive Property of multiplication and addition, you can sum those two together and multiply this single sum by all of its continuations.
For every possible last substring, it adds the sum of all splits ending with that by adding its probability multiplied by the sum of all probabilities of previous paths. (alternative phrasing would be appreciated. my python is better than my english..)
A:
First, profile to find the bottleneck.
If the bottleneck is simply the massive number of possible partitions, I recommend parallelization, possibly via multiprocessing. If that's still not enough, you might look into a Beowulf cluster.
If the bottleneck is just that the calculation is slow, try shelling out to C. It's pretty easy to do via ctypes.
Also, I'm not really sure how you're storing the partitions, but you could probably squash memory consumption a pretty good bit by using one string and a suffix array. If your bottleneck is swapping and/or cache misses, that might be a big win.
A:
Your substrings are going to be reused over and over again by the longer strings, so caching the values using a memoizing technique seems like an obvious thing to try. This is just a time-space trade off. The simplest implementation is to use a dictionary to cache values as you calculate them. Do a dictionary lookup for every string calculation; if it's not in the dictionary, calculate and add it. Subsequent calls will make use of the pre-computed value. If the dictionary lookup is faster than the calculation, you're in luck.
I realise you are using Python, but... as a side note that may be of interest, if you do this in Perl, you don't even have to write any code; the built in Memoize module will do the caching for you!
A:
You may get a minor reduction of the amount of computation by a small refactoring based on associative properties of arithmetic (and string concatenation) though I'm not sure it will be a life-changer. The core idea would be as follows:
consider a longish string e.g. 'abcdefghik', 10-long, for definiteness w/o loss of generality. In a naive approach you'd be multiplying p(a) by the many partitions of the 9-tail, p(ab) by the many partitions of the 8-tail, etc; in particular p(a) and p(b) will be multiplying exactly the same partitions of the 8-tail (all of them) as p(ab) will -- 3 multiplications and two sums among them. So factor that out:
(p(ab) + p(a) * p(b)) * (partitions of the 8-tail)
and we're down to 2 multiplications and 1 sum for this part, having saved 1 product and 1 sum. to cover all partitions with a split point just right of 'b'. When it comes to partitions with a split just right of 'c',
(p(abc) + p(ab) * p(c) + p(a) * (p(b)*p(c)+p(bc)) * (partitions of the 7-tail)
the savings mount, partly thanks to the internal refactoring -- though of course one must be careful about double-counting. I'm thinking that this approach may be generalized -- start with the midpoint and consider all partitions that have a split there, separately (and recursively) for the left and right part, multiplying and summing; then add all partitions that DON'T have a split there, e.g. in the example, the halves being 'abcde' on the left and 'fghik' on the right, the second part is about all partitions where 'ef' are together rather than apart -- so "collapse" all probabilities by considering that 'ef' as a new 'superletter' X, and you're left with a string one shorter, 'abcdXghik' (of course the probabilities for the substrings of THAT map directly to the originals, e.g. the p(cdXg) in the new string is just exactly the p(cdefg) in the original).
A:
You should look into the itertools module. It can create a generator for you that is very fast. Given your input string, it will provide you with all possible permutations. Depending on what you need, there is also a combinations() generator. I'm not quite sure if you're looking at "b|ca" when you're looking at "abc," but either way, this module may prove useful to you.
|
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string?
|
I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition.
For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers.
Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters.
Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now.
In response to some comments here is some more information:
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc').
|
[
"A Dynamic Programming solution (if I understood the question right):\ndef dynProgSolution(text, probs):\n probUpTo = [1]\n for i in range(1, len(text)+1):\n cur = sum(v*probs[text[k:i]] for k, v in enumerate(probUpTo))\n probUpTo.append(cur)\n return probUpTo[-1]\n\nprint dynProgSolution(\n 'abc',\n {'a': 0.1, 'b': 0.2, 'c': 0.3,\n 'ab': 0.4, 'bc': 0.5, 'abc': 0.6}\n )\n\nThe complexity is O(N2) so it will easily solve the problem for N=20.\nHow why does this work:\n\nEverything you will multiply by probs['a']*probs['b'] you will also multiply by probs['ab']\nThanks to the Distributive Property of multiplication and addition, you can sum those two together and multiply this single sum by all of its continuations.\nFor every possible last substring, it adds the sum of all splits ending with that by adding its probability multiplied by the sum of all probabilities of previous paths. (alternative phrasing would be appreciated. my python is better than my english..)\n\n",
"First, profile to find the bottleneck.\nIf the bottleneck is simply the massive number of possible partitions, I recommend parallelization, possibly via multiprocessing. If that's still not enough, you might look into a Beowulf cluster.\nIf the bottleneck is just that the calculation is slow, try shelling out to C. It's pretty easy to do via ctypes.\nAlso, I'm not really sure how you're storing the partitions, but you could probably squash memory consumption a pretty good bit by using one string and a suffix array. If your bottleneck is swapping and/or cache misses, that might be a big win.\n",
"Your substrings are going to be reused over and over again by the longer strings, so caching the values using a memoizing technique seems like an obvious thing to try. This is just a time-space trade off. The simplest implementation is to use a dictionary to cache values as you calculate them. Do a dictionary lookup for every string calculation; if it's not in the dictionary, calculate and add it. Subsequent calls will make use of the pre-computed value. If the dictionary lookup is faster than the calculation, you're in luck.\nI realise you are using Python, but... as a side note that may be of interest, if you do this in Perl, you don't even have to write any code; the built in Memoize module will do the caching for you!\n",
"You may get a minor reduction of the amount of computation by a small refactoring based on associative properties of arithmetic (and string concatenation) though I'm not sure it will be a life-changer. The core idea would be as follows:\nconsider a longish string e.g. 'abcdefghik', 10-long, for definiteness w/o loss of generality. In a naive approach you'd be multiplying p(a) by the many partitions of the 9-tail, p(ab) by the many partitions of the 8-tail, etc; in particular p(a) and p(b) will be multiplying exactly the same partitions of the 8-tail (all of them) as p(ab) will -- 3 multiplications and two sums among them. So factor that out:\n(p(ab) + p(a) * p(b)) * (partitions of the 8-tail)\n\nand we're down to 2 multiplications and 1 sum for this part, having saved 1 product and 1 sum. to cover all partitions with a split point just right of 'b'. When it comes to partitions with a split just right of 'c',\n(p(abc) + p(ab) * p(c) + p(a) * (p(b)*p(c)+p(bc)) * (partitions of the 7-tail)\n\nthe savings mount, partly thanks to the internal refactoring -- though of course one must be careful about double-counting. I'm thinking that this approach may be generalized -- start with the midpoint and consider all partitions that have a split there, separately (and recursively) for the left and right part, multiplying and summing; then add all partitions that DON'T have a split there, e.g. in the example, the halves being 'abcde' on the left and 'fghik' on the right, the second part is about all partitions where 'ef' are together rather than apart -- so \"collapse\" all probabilities by considering that 'ef' as a new 'superletter' X, and you're left with a string one shorter, 'abcdXghik' (of course the probabilities for the substrings of THAT map directly to the originals, e.g. the p(cdXg) in the new string is just exactly the p(cdefg) in the original).\n",
"You should look into the itertools module. It can create a generator for you that is very fast. Given your input string, it will provide you with all possible permutations. Depending on what you need, there is also a combinations() generator. I'm not quite sure if you're looking at \"b|ca\" when you're looking at \"abc,\" but either way, this module may prove useful to you.\n"
] |
[
5,
3,
1,
1,
0
] |
[] |
[] |
[
"partitioning",
"python",
"string"
] |
stackoverflow_0001223007_partitioning_python_string.txt
|
Q:
How to write native newline character to a file descriptor in Python?
The os.write function can be used to writes bytes into a file descriptor (not file object). If I execute os.write(fd, '\n'), only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux.
What is the best way to achieve this?
I'm using Python 2.6, but I'm also wondering if Python 3 has a different solution.
A:
Use this
import os
os.write(fd, os.linesep)
A:
How about os.write(<file descriptor>, os.linesep)? (import os is unnecessary because you seem to have already imported it, otherwise you'd be getting errors using os.write to begin with.)
|
How to write native newline character to a file descriptor in Python?
|
The os.write function can be used to writes bytes into a file descriptor (not file object). If I execute os.write(fd, '\n'), only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux.
What is the best way to achieve this?
I'm using Python 2.6, but I'm also wondering if Python 3 has a different solution.
|
[
"Use this\nimport os\nos.write(fd, os.linesep)\n\n",
"How about os.write(<file descriptor>, os.linesep)? (import os is unnecessary because you seem to have already imported it, otherwise you'd be getting errors using os.write to begin with.)\n"
] |
[
85,
8
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001223289_python.txt
|
Q:
How to agnostically link any object/Model from another Django Model?
I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work out which page, you require the URL.
The problem comes when you're no longer dealing with "pages" (be those FlatPages pages, or something else), but rather instances from another Model. For example if I have a Model of products, I may wish to create a detail page that has multiple editable regions within.
I could build those regions into the Model but in my case, there are several Models and is a lot of variance in how much data I want to show.
Therefore, I want to build the CMS at template level and specify what a block (an editable region) is based on the instance of "page" or the model it uses.
I've had the idea that perhaps I could dump custom template tags on the page like this:
{% block unique_object "unique placeholder name" %}
And that would find a "block" based on the two arguments passed in. An example:
<h1>{{ product_instance.name }}</h1>
{% block product_instance "detail: product short description" %}
{% block product_instance "detail: product video" %}
{% block product_instance "detail: product long description" %}
Sounds spiffy, right? Well the problem I'm running into is how do I create a "key" for a zone so I can pull the correct block out? I'll be dealing with a completely unknown object (it could be a "page" object, a URL, a model instance, anything - it could even be a boat</fg>).
Other Django micro-applications must do this. You can tag anything with django-tagging, right? I've tried to understand how that works but I'm drawing blanks.
So, firstly, am I mad? And assuming I not, and this looks like a relatively sane idea to persue, how should I go about linking an object+string to a block/editable-region?
Note: Editing will be done on-the-page so there's no real issue in letting the users edit the zones. I won't have to do any reverse-mumbo-jumbo in the admin. My eventual dream is to allow a third argument to specify what sort of content area this is (text, image, video, etc). If you have any comments on any of this, I'm happy to read them!
A:
django-tagging uses Django's contenttypes framework. The docs do a much better job of explaining it than I can, but the simplest description of it would be "generic foreign key that can point to any other model."
This may be what you are looking for, but from your description it also sounds like you want to do something very similar to some other existing projects:
django-flatblocks ("... acts like django.contrib.flatpages but for parts of a page; like an editable help box you want show alongside the main content.")
django-better-chunks ("Think of it as flatpages for small bits of reusable content you might want to insert into your templates and manage from the admin interface.")
and so on. If these are similar then they'll make a good starting point for you.
A:
You want a way to display some object-specific content on a generic template, given a specific object, correct?
In order to support both models and other objects, we need two intermediate models; one to handle strings, and one to handle models. We could do it with one model, but this is less performant. These models will provide the link between content and string/model.
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
CONTENT_TYPE_CHOICES = (
("video", "Video"),
("text", "Text"),
("image", "Image"),
)
def _get_template(name, type):
"Returns a list of templates to load given a name and a type"
return ["%s_%s.html" % (type, name), "%s.html" % name, "%s.html" % type]
class ModelContentLink(models.Model):
key = models.CharField(max_length=255) # Or whatever you find appropriate
type = models.CharField(max_length=31, choices= CONTENT_TYPE_CHOICES)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
def get_template(self):
model_name = self.object.__class__.__name__.lower()
return _get_template(model_name, self.type)
class StringContentLink(models.Model):
key = models.CharField(max_length=255) # Or whatever length you find appropriate
type = models.CharField(max_length=31, choices= CONTENT_TYPE_CHOICES)
content = models.TextField()
def get_template(self):
return _get_template(self.content, self.type)
Now, all we need is a template tag to grab these, and then try to load the templates given by the models' get_template() method. I'm a bit pressed on time so I'll leave it at this and update it in ~1 hour. Let me know if you think this approach seems fine.
A:
It's pretty straightforward to use the contenttypes framework to implement the lookup strategy you are describing:
class Block(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey() # not actually used here, but may be handy
key = models.CharField(max_length=255)
... other fields ...
class Meta:
unique_together = ('content_type', 'object_id', 'key')
def lookup_block(object, key):
return Block.objects.get(content_type=ContentType.objects.get_for_model(object),
object_id=object.pk,
key=key)
@register.simple_tag
def block(object, key)
block = lookup_block(object, key)
... generate template content using 'block' ...
One gotcha to be aware of is that you can't use the object field in the Block.objects.get call, because it's not a real database field. You must use content_type and object_id.
I called the model Block, but if you have some cases where more than one unique (object, key) tuple maps to the same block, it may in fact be an intermediate model that itself has a ForeignKey to your actual Block model or to the appropriate model in a helper app like the ones Van Gale has mentioned.
|
How to agnostically link any object/Model from another Django Model?
|
I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work out which page, you require the URL.
The problem comes when you're no longer dealing with "pages" (be those FlatPages pages, or something else), but rather instances from another Model. For example if I have a Model of products, I may wish to create a detail page that has multiple editable regions within.
I could build those regions into the Model but in my case, there are several Models and is a lot of variance in how much data I want to show.
Therefore, I want to build the CMS at template level and specify what a block (an editable region) is based on the instance of "page" or the model it uses.
I've had the idea that perhaps I could dump custom template tags on the page like this:
{% block unique_object "unique placeholder name" %}
And that would find a "block" based on the two arguments passed in. An example:
<h1>{{ product_instance.name }}</h1>
{% block product_instance "detail: product short description" %}
{% block product_instance "detail: product video" %}
{% block product_instance "detail: product long description" %}
Sounds spiffy, right? Well the problem I'm running into is how do I create a "key" for a zone so I can pull the correct block out? I'll be dealing with a completely unknown object (it could be a "page" object, a URL, a model instance, anything - it could even be a boat</fg>).
Other Django micro-applications must do this. You can tag anything with django-tagging, right? I've tried to understand how that works but I'm drawing blanks.
So, firstly, am I mad? And assuming I not, and this looks like a relatively sane idea to persue, how should I go about linking an object+string to a block/editable-region?
Note: Editing will be done on-the-page so there's no real issue in letting the users edit the zones. I won't have to do any reverse-mumbo-jumbo in the admin. My eventual dream is to allow a third argument to specify what sort of content area this is (text, image, video, etc). If you have any comments on any of this, I'm happy to read them!
|
[
"django-tagging uses Django's contenttypes framework. The docs do a much better job of explaining it than I can, but the simplest description of it would be \"generic foreign key that can point to any other model.\"\nThis may be what you are looking for, but from your description it also sounds like you want to do something very similar to some other existing projects:\n\ndjango-flatblocks (\"... acts like django.contrib.flatpages but for parts of a page; like an editable help box you want show alongside the main content.\")\ndjango-better-chunks (\"Think of it as flatpages for small bits of reusable content you might want to insert into your templates and manage from the admin interface.\")\n\nand so on. If these are similar then they'll make a good starting point for you.\n",
"You want a way to display some object-specific content on a generic template, given a specific object, correct?\nIn order to support both models and other objects, we need two intermediate models; one to handle strings, and one to handle models. We could do it with one model, but this is less performant. These models will provide the link between content and string/model.\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nCONTENT_TYPE_CHOICES = (\n (\"video\", \"Video\"),\n (\"text\", \"Text\"),\n (\"image\", \"Image\"),\n)\n\ndef _get_template(name, type):\n \"Returns a list of templates to load given a name and a type\"\n return [\"%s_%s.html\" % (type, name), \"%s.html\" % name, \"%s.html\" % type]\n\nclass ModelContentLink(models.Model):\n key = models.CharField(max_length=255) # Or whatever you find appropriate\n type = models.CharField(max_length=31, choices= CONTENT_TYPE_CHOICES)\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n object = generic.GenericForeignKey('content_type', 'object_id')\n\n def get_template(self):\n model_name = self.object.__class__.__name__.lower()\n return _get_template(model_name, self.type)\n\nclass StringContentLink(models.Model):\n key = models.CharField(max_length=255) # Or whatever length you find appropriate\n type = models.CharField(max_length=31, choices= CONTENT_TYPE_CHOICES)\n content = models.TextField()\n\n def get_template(self):\n return _get_template(self.content, self.type)\n\nNow, all we need is a template tag to grab these, and then try to load the templates given by the models' get_template() method. I'm a bit pressed on time so I'll leave it at this and update it in ~1 hour. Let me know if you think this approach seems fine.\n",
"It's pretty straightforward to use the contenttypes framework to implement the lookup strategy you are describing:\nclass Block(models.Model):\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n object = generic.GenericForeignKey() # not actually used here, but may be handy\n key = models.CharField(max_length=255)\n ... other fields ...\n\n class Meta:\n unique_together = ('content_type', 'object_id', 'key')\n\ndef lookup_block(object, key):\n return Block.objects.get(content_type=ContentType.objects.get_for_model(object),\n object_id=object.pk,\n key=key)\n\[email protected]_tag\ndef block(object, key)\n block = lookup_block(object, key)\n ... generate template content using 'block' ...\n\nOne gotcha to be aware of is that you can't use the object field in the Block.objects.get call, because it's not a real database field. You must use content_type and object_id.\nI called the model Block, but if you have some cases where more than one unique (object, key) tuple maps to the same block, it may in fact be an intermediate model that itself has a ForeignKey to your actual Block model or to the appropriate model in a helper app like the ones Van Gale has mentioned.\n"
] |
[
6,
2,
2
] |
[] |
[] |
[
"content_management_system",
"django",
"django_models",
"python"
] |
stackoverflow_0000969211_content_management_system_django_django_models_python.txt
|
Q:
Python string templater
I'm using this REST web service, which returns various templated strings as urls, for example:
"http://api.app.com/{foo}"
In Ruby, I can then use
url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar')
to get
"http://api.app.com/bar"
Is there any way to do this in Python? I know about %() templates, but obviously they're not working here.
A:
In python 2.6 you can do this if you need exactly that syntax
from string import Formatter
f = Formatter()
f.format("http://api.app.com/{foo}", foo="bar")
If you need to use an earlier python version then you can either copy the 2.6 formatter class or hand roll a parser/regex to do it.
A:
Don't use a quick hack.
What is used there (and implemented by Addressable) are URI Templates. There seem to be several libs for this in python, for example: uri-templates. described_routes_py also has a parser for them.
A:
I cannot give you a perfect solution but you could try using string.Template.
You either pre-process your incoming URL and then use string.Template directly, like
In [6]: url="http://api.app.com/{foo}"
In [7]: up=string.Template(re.sub("{", "${", url))
In [8]: up.substitute({"foo":"bar"})
Out[8]: 'http://api.app.com/bar'
taking advantage of the default "${...}" syntax for replacement identifiers. Or you subclass string.Template to control the identifier pattern, like
class MyTemplate(string.Template):
delimiter = ...
pattern = ...
but I haven't figured that out.
|
Python string templater
|
I'm using this REST web service, which returns various templated strings as urls, for example:
"http://api.app.com/{foo}"
In Ruby, I can then use
url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar')
to get
"http://api.app.com/bar"
Is there any way to do this in Python? I know about %() templates, but obviously they're not working here.
|
[
"In python 2.6 you can do this if you need exactly that syntax\nfrom string import Formatter\nf = Formatter()\nf.format(\"http://api.app.com/{foo}\", foo=\"bar\")\n\nIf you need to use an earlier python version then you can either copy the 2.6 formatter class or hand roll a parser/regex to do it.\n",
"Don't use a quick hack.\nWhat is used there (and implemented by Addressable) are URI Templates. There seem to be several libs for this in python, for example: uri-templates. described_routes_py also has a parser for them.\n",
"I cannot give you a perfect solution but you could try using string.Template.\nYou either pre-process your incoming URL and then use string.Template directly, like\nIn [6]: url=\"http://api.app.com/{foo}\"\nIn [7]: up=string.Template(re.sub(\"{\", \"${\", url))\nIn [8]: up.substitute({\"foo\":\"bar\"})\nOut[8]: 'http://api.app.com/bar'\n\ntaking advantage of the default \"${...}\" syntax for replacement identifiers. Or you subclass string.Template to control the identifier pattern, like\nclass MyTemplate(string.Template):\n delimiter = ...\n pattern = ...\n\nbut I haven't figured that out.\n"
] |
[
4,
2,
0
] |
[] |
[] |
[
"python",
"ruby",
"string",
"templates"
] |
stackoverflow_0001218457_python_ruby_string_templates.txt
|
Q:
Python TypeError unsupported operand type(s) for %: 'file' and 'unicode'
I'm working on a django field validation and I can't figure out why I'm getting a type error for this section:
def clean_tid(self):
data = self.cleaned_data['tid']
stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN") % data
result = stdout_handel.read()
Do I have to convert data somehow before I can pass it in as a string variable?
A:
Check your parenthesis.
Wrong
stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN") % data
Might be right.
stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN" % data )
A:
Just a small tip - it's better to use subprocess module and Popen class instead of os.popen function. More details here (docs).
|
Python TypeError unsupported operand type(s) for %: 'file' and 'unicode'
|
I'm working on a django field validation and I can't figure out why I'm getting a type error for this section:
def clean_tid(self):
data = self.cleaned_data['tid']
stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN") % data
result = stdout_handel.read()
Do I have to convert data somehow before I can pass it in as a string variable?
|
[
"Check your parenthesis.\nWrong\nstdout_handel = os.popen(\"/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN\") % data\n\nMight be right.\nstdout_handel = os.popen(\"/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN\" % data )\n\n",
"Just a small tip - it's better to use subprocess module and Popen class instead of os.popen function. More details here (docs).\n"
] |
[
1,
1
] |
[] |
[] |
[
"django",
"python",
"typeerror",
"unicode"
] |
stackoverflow_0001223563_django_python_typeerror_unicode.txt
|
Q:
"Watching" program being processed line-by-line?
I'm looking for a debugging tool that will run my Python app, but display which line is currently being processed -- like an automatically stepping debugger. Basically I want to see what is going on, but be able to jump in if a traceback occurs.
A:
Winpdb is a good python debugger. It is written in Python under the GPL, so adding the automatic stepping functionality you want should not be too complicated.
A:
I think you're looking for the pdb module.
A:
"Basically I want to see what is going on, but be able to jump in if a traceback occurs."
Here's a radical thought: Don't.
"Watching" is a crutch. You should be writing small sections of code that you know will work. Then put those together.
Watching sometimes results from "I'm not sure what Python's really doing", so there's an urge to "watch" execution and see what's happening. Other times watching results from writing a script that's too big and complex without proper decomposition. Sometimes watching results from having a detailed specification which was translated into Python without a deep understanding. I've seen people doing these; of course, there are lots more reasons.
The advice, however, is the same for all:
Break things into small pieces,
usually classes of functions. Make
them simple enough that you can
actually understand what Python is
doing.
Knit them together to create your
larger application from pieces you
actually understand.
Watching will limit your ability to actually write working software. It will -- in a very real way -- limit you to trivial programming exercises. It's not a good learning tool; and it's a perfectly awful way to create production code.
Bottom Line.
Don't pursue "watching". Decompose into smaller pieces so you don't need to watch.
A:
The integrated debugger in Wing IDE is quite versatile and nice to work with. (The Wing IDE 101 version is freeware.)
A:
There is also a very nice debugger in The Python Eclipse plugin.
A:
Try IPython alongwith ipdb
|
"Watching" program being processed line-by-line?
|
I'm looking for a debugging tool that will run my Python app, but display which line is currently being processed -- like an automatically stepping debugger. Basically I want to see what is going on, but be able to jump in if a traceback occurs.
|
[
"Winpdb is a good python debugger. It is written in Python under the GPL, so adding the automatic stepping functionality you want should not be too complicated. \n",
"I think you're looking for the pdb module.\n",
"\"Basically I want to see what is going on, but be able to jump in if a traceback occurs.\"\nHere's a radical thought: Don't.\n\"Watching\" is a crutch. You should be writing small sections of code that you know will work. Then put those together.\nWatching sometimes results from \"I'm not sure what Python's really doing\", so there's an urge to \"watch\" execution and see what's happening. Other times watching results from writing a script that's too big and complex without proper decomposition. Sometimes watching results from having a detailed specification which was translated into Python without a deep understanding. I've seen people doing these; of course, there are lots more reasons.\nThe advice, however, is the same for all:\n\nBreak things into small pieces,\nusually classes of functions. Make\nthem simple enough that you can\nactually understand what Python is\ndoing. \nKnit them together to create your\nlarger application from pieces you\nactually understand.\n\nWatching will limit your ability to actually write working software. It will -- in a very real way -- limit you to trivial programming exercises. It's not a good learning tool; and it's a perfectly awful way to create production code.\nBottom Line.\nDon't pursue \"watching\". Decompose into smaller pieces so you don't need to watch.\n",
"The integrated debugger in Wing IDE is quite versatile and nice to work with. (The Wing IDE 101 version is freeware.)\n",
"There is also a very nice debugger in The Python Eclipse plugin.\n",
"Try IPython alongwith ipdb\n"
] |
[
3,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"debugging",
"python"
] |
stackoverflow_0001220465_debugging_python.txt
|
Q:
Lightweight markup language for Python
Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to enter any (html) text:
my_text = cgidata.getvalue('my_text', 'default_text')
ftable.AddRow([Label(_('Enter your text')),
TextArea('my_text', my_text, rows=8, cols=60).Format()])
How can I change this so that only some (safe, eventually lightweight) markup is allowed? All suggestions including sanitizers are welcome, as long as it easily integrates with Python.
A:
Use the python markdown implementation
import markdown
mode = "remove" # or "replace" or "escape"
md = markdown.Markdown(safe_mode=mode)
html = md.convert(text)
It is very flexible, you can use various extensions, create your own etc.
A:
You could use restructured text . I'm not sure if it has a sanitizing option, but it's well supported by Python, and it generates all sorts of formats.
A:
This simple sanitizing function uses a whitelist and is roughly the same as the solution of python-html-sanitizer-scrubber-filter, but also allows to limit the use of attributes (since you probably don't want someone to use, among others, the style attribute):
from BeautifulSoup import BeautifulSoup
def sanitize_html(value):
valid_tags = 'p i b strong a pre br'.split()
valid_attrs = 'href src'.split()
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in valid_tags:
tag.hidden = True
tag.attrs = [(attr, val) for attr, val in tag.attrs if attr in valid_attrs]
return soup.renderContents().decode('utf8').replace('javascript:', '')
|
Lightweight markup language for Python
|
Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to enter any (html) text:
my_text = cgidata.getvalue('my_text', 'default_text')
ftable.AddRow([Label(_('Enter your text')),
TextArea('my_text', my_text, rows=8, cols=60).Format()])
How can I change this so that only some (safe, eventually lightweight) markup is allowed? All suggestions including sanitizers are welcome, as long as it easily integrates with Python.
|
[
"Use the python markdown implementation\nimport markdown\nmode = \"remove\" # or \"replace\" or \"escape\"\nmd = markdown.Markdown(safe_mode=mode)\nhtml = md.convert(text)\n\nIt is very flexible, you can use various extensions, create your own etc.\n",
"You could use restructured text . I'm not sure if it has a sanitizing option, but it's well supported by Python, and it generates all sorts of formats.\n",
"This simple sanitizing function uses a whitelist and is roughly the same as the solution of python-html-sanitizer-scrubber-filter, but also allows to limit the use of attributes (since you probably don't want someone to use, among others, the style attribute):\nfrom BeautifulSoup import BeautifulSoup\n\ndef sanitize_html(value):\n valid_tags = 'p i b strong a pre br'.split()\n valid_attrs = 'href src'.split()\n soup = BeautifulSoup(value)\n for tag in soup.findAll(True):\n if tag.name not in valid_tags:\n tag.hidden = True\n tag.attrs = [(attr, val) for attr, val in tag.attrs if attr in valid_attrs]\n return soup.renderContents().decode('utf8').replace('javascript:', '')\n\n"
] |
[
8,
2,
1
] |
[] |
[] |
[
"html",
"markup",
"python"
] |
stackoverflow_0001223741_html_markup_python.txt
|
Q:
How can I display updating output of a slow script using Pylons?
I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once.
I found how to access the output of the command in Python with the answer to this question:
How can I perform a ping or traceroute in python, accessing the output as it is produced?
Now I need to find a way to get this information to the browser as it is being generated. I was planning on using jQuery's loadContent() to load the output of a script into a . The problem is that Pylons controllers use return so the output has to be complete before Pylons renders the page and the web server responds to the client with the content.
Is there any way to have a page display content as it is generated within Pylons or will this have to be done with scripting outside of Pylons?
Basically, I'm trying to do something like this:
http://network-tools.com/default.asp?prog=trace&host=www.bbc.co.uk
A:
pexpect will let you get the output as it comes, with no buffering.
To update info promptly on the user's browser, you need javascript on that browser sending appropriate AJAX requests to your server (dojo or jquery will make that easier, though they're not strictly required) and updating the page as new responses come -- without client-side cooperation (and JS + AJAX is the simplest way to get that cooperation), there's no sensible way to do it on the server side alone.
So the general approach is: send AJAX query from browser, have server respond as soon as it has one more line, JS on the browser updates contents then immediately sends another query, repeat until server responds with an "I'm all done" marker (e.g. an "empty" response may work for that purpose).
A:
You may want to look at this faq entry. Then with JS, you always clear the screen before writing new stuff.
A:
I haven't tried it with pylons, but you could try to show the output of the slow component in an iframe on the page (using mime type text/plain) and yield each chunk to the iframe as it is generated. For fun I just put this together as a
WHIFF demo. Here is the slowly generated web content wsgi application:
import time
def slow(env, start_response):
start_response("200 OK", [('Content-Type', 'text/plain')])
return slow_generator()
def slow_generator():
yield "slowly generating 20 timestamps\n"
for i in range(20):
yield "%s: %s\n" % (i, time.ctime())
time.sleep(1)
yield "done!"
__wsgi__ = slow
This file is deployed on my laptop at: http://aaron.oirt.rutgers.edu/myapp/root/misc/slow.
Here is the WHIFF configuration template which includes the slow page in an
iframe:
{{env whiff.content_type: "text/html"/}}
Here is an iframe with slowly generated content:
<hr>
<iframe frameborder="1" height="300px" width="300px" scrolling="yes"
style="background-color:#99dddd;"
src="slow"
></iframe>
<hr>
Isn't that cool?
This is deployed on my laptop at http://aaron.oirt.rutgers.edu/myapp/root/misc/showSlowly.
hmmm. I just tried the above link in safari and it didn't work right... apparently there are some browser differences... Seems to work on Firefox at least...
|
How can I display updating output of a slow script using Pylons?
|
I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once.
I found how to access the output of the command in Python with the answer to this question:
How can I perform a ping or traceroute in python, accessing the output as it is produced?
Now I need to find a way to get this information to the browser as it is being generated. I was planning on using jQuery's loadContent() to load the output of a script into a . The problem is that Pylons controllers use return so the output has to be complete before Pylons renders the page and the web server responds to the client with the content.
Is there any way to have a page display content as it is generated within Pylons or will this have to be done with scripting outside of Pylons?
Basically, I'm trying to do something like this:
http://network-tools.com/default.asp?prog=trace&host=www.bbc.co.uk
|
[
"pexpect will let you get the output as it comes, with no buffering.\nTo update info promptly on the user's browser, you need javascript on that browser sending appropriate AJAX requests to your server (dojo or jquery will make that easier, though they're not strictly required) and updating the page as new responses come -- without client-side cooperation (and JS + AJAX is the simplest way to get that cooperation), there's no sensible way to do it on the server side alone.\nSo the general approach is: send AJAX query from browser, have server respond as soon as it has one more line, JS on the browser updates contents then immediately sends another query, repeat until server responds with an \"I'm all done\" marker (e.g. an \"empty\" response may work for that purpose).\n",
"You may want to look at this faq entry. Then with JS, you always clear the screen before writing new stuff.\n",
"I haven't tried it with pylons, but you could try to show the output of the slow component in an iframe on the page (using mime type text/plain) and yield each chunk to the iframe as it is generated. For fun I just put this together as a \nWHIFF demo. Here is the slowly generated web content wsgi application:\nimport time\n\ndef slow(env, start_response):\n start_response(\"200 OK\", [('Content-Type', 'text/plain')])\n return slow_generator()\n\ndef slow_generator():\n yield \"slowly generating 20 timestamps\\n\"\n for i in range(20):\n yield \"%s: %s\\n\" % (i, time.ctime())\n time.sleep(1)\n yield \"done!\"\n\n__wsgi__ = slow\n\nThis file is deployed on my laptop at: http://aaron.oirt.rutgers.edu/myapp/root/misc/slow.\nHere is the WHIFF configuration template which includes the slow page in an\niframe:\n{{env whiff.content_type: \"text/html\"/}}\n\nHere is an iframe with slowly generated content:\n<hr>\n<iframe frameborder=\"1\" height=\"300px\" width=\"300px\" scrolling=\"yes\"\nstyle=\"background-color:#99dddd;\"\nsrc=\"slow\"\n></iframe>\n<hr>\nIsn't that cool?\n\nThis is deployed on my laptop at http://aaron.oirt.rutgers.edu/myapp/root/misc/showSlowly.\nhmmm. I just tried the above link in safari and it didn't work right... apparently there are some browser differences... Seems to work on Firefox at least...\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0001175748_pylons_python.txt
|
Q:
Sending an email from Pylons
I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email?
A:
What you want is turbomail. In documentation you have an entry where is explains how to integrate it with Pylons.
A:
Can't you just use standard Python library modules, email to prepare the mail and smtp to send it? What extra value beyond that are you looking for from the "built-in feature"?
A:
Try this: http://jjinux.blogspot.com/2009/02/python-logging-to-email-in-pylons.html
|
Sending an email from Pylons
|
I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email?
|
[
"What you want is turbomail. In documentation you have an entry where is explains how to integrate it with Pylons.\n",
"Can't you just use standard Python library modules, email to prepare the mail and smtp to send it? What extra value beyond that are you looking for from the \"built-in feature\"?\n",
"Try this: http://jjinux.blogspot.com/2009/02/python-logging-to-email-in-pylons.html\n"
] |
[
5,
2,
2
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0001089576_pylons_python.txt
|
Q:
Trying to import module with the same name as a built-in module causes an import error
I have a module that conflicts with a built-in module. For example, a myapp.email module defined in myapp/email.py.
I can reference myapp.email anywhere in my code without issue. However, I need to reference the built-in email module from my email module.
# myapp/email.py
from email import message_from_string
It only finds itself, and therefore raises an ImportError, since myapp.email doesn't have a message_from_string method. import email causes the same issue when I try email.message_from_string.
Is there any native support to do this in Python, or am I stuck with renaming my "email" module to something more specific?
A:
You will want to read about Absolute and Relative Imports which addresses this very problem. Use:
from __future__ import absolute_import
Using that, any unadorned package name will always refer to the top level package. You will then need to use relative imports (from .email import ...) to access your own package.
NOTE: The above from ... line needs to be put into any 2.x Python .py files above the import ... lines you're using. In Python 3.x this is the default behavior and so is no longer needed.
|
Trying to import module with the same name as a built-in module causes an import error
|
I have a module that conflicts with a built-in module. For example, a myapp.email module defined in myapp/email.py.
I can reference myapp.email anywhere in my code without issue. However, I need to reference the built-in email module from my email module.
# myapp/email.py
from email import message_from_string
It only finds itself, and therefore raises an ImportError, since myapp.email doesn't have a message_from_string method. import email causes the same issue when I try email.message_from_string.
Is there any native support to do this in Python, or am I stuck with renaming my "email" module to something more specific?
|
[
"You will want to read about Absolute and Relative Imports which addresses this very problem. Use:\nfrom __future__ import absolute_import\n\nUsing that, any unadorned package name will always refer to the top level package. You will then need to use relative imports (from .email import ...) to access your own package.\nNOTE: The above from ... line needs to be put into any 2.x Python .py files above the import ... lines you're using. In Python 3.x this is the default behavior and so is no longer needed.\n"
] |
[
101
] |
[] |
[] |
[
"python",
"python_import"
] |
stackoverflow_0001224741_python_python_import.txt
|
Q:
How do I associate input to a Form with a Model in Django?
In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table?
For example:
class PhoneNumber(models.Model):
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=30)
PhoneNumber = models.CharField(max_length=20)
class PhoneNumber(forms.Form):
FirstName = forms.CharField(max_length=30)
LastName = forms.CharField(max_length=30)
PhoneNumber = forms.CharField(max_length=20)
I know there is a class for creating a form from the the model, but even there I'm unclear on how the data actually gets to the database. And I'd like to understand the inner workings before I move on to the time-savers. If there is a simple example of how this works in the docs, I've missed it.
Thanks.
UPDATED:
To be clear -- I do know about the ModelForm tool, I'm trying to figure out how to do this without that -- in part so I can better understand what it's doing in the first place.
ANSWERED:
With the help of the anwers, I arrived at this solution:
Form definition:
class ThisForm(forms.Form)
[various Field assignments]
model = ThisModel()
Code in views to save entered data to database:
if request_method == 'POST':
form = ThisForm(request.POST)
if form.is_valid():
for key, value in form.cleaned_data.items():
setattr(form.model, key, value)
form.model.save(form.model)
After this the data entered in the browser form was in the database table.
Note that the call of the model's save() method required passage of the model itself as an argument. I have no idea why.
CAVEAT: I'm a newbie. This succeeded in getting data from a browser to a database table, but God only knows what I've neglected or missed or outright broken along the way. ModelForm definitely seems like a much cleaner solution.
A:
Back when I first used Forms and Models (without using ModelForm), what I remember doing was checking if the form was valid, which would set your cleaned data, manually moving the data from the form to the model (or whatever other processing you want to do), and then saving the model. As you can tell, this was extremely tedious when your form exactly (or even closely) matches your model. By using the ModelForm (since you said you weren't quite sure how it worked), when you save the ModelForm, it instantiates an object with the form data according to the model spec and then saves that model for you. So all-in-all, the flow of data goes from the HTML form, to the Django Form, to the Django Model, to the DB.
Some actual code for your questions:
To get the browser form data into the form object:
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
model.attr = form.cleaned_data['attr']
model.attr2 = form.cleaned_data['attr2']
model.save()
else:
form = SomeForm()
return render_to_response('page.html', {'form': form, })
In the template page you can do things like this with the form:
<form method="POST">
{{ form.as_p }}
<input type="submit"/>
</form>
That's just one example that I pulled from here.
A:
I'm not sure which class do you mean. I know that there were a helper, something like form_for_model (don't really remember the exact name; that was way before 1.0 version was released). Right now I'd it that way:
import myproject.myapp.models as models
class PhoneNumberForm(forms.ModelForm):
class Meta:
model = models.PhoneNumber
To see the metaclass magic behind, you'd have to look into the code as there is a lot to explain :]. The constructor of the form can take instance argument. Passing it will make the form operate on an existing record rather than creating a new one. More info here.
A:
I think ModelForm.save documentation should explain it. With its base class (Form) you would need to use the Form.cleaned_data() to get the field values and set them to appropriate Model fields "by hand". ModelForm does all that for you.
A:
The Django documentation is pretty clear on this subject. However, here is a rough guide for you to get started: You can either override the form's save method or implement that functionality in the view.
if form.is_valid() # validation - first the fields, then the form itself is validated
form.save()
inside the form:
def save(self, *args, **kwargs):
foo = Foo()
foo.somefield = self.cleaned_data['somefield']
foo.otherfield = self.cleaned_data['otherfield']
...
return foo.save()
|
How do I associate input to a Form with a Model in Django?
|
In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table?
For example:
class PhoneNumber(models.Model):
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=30)
PhoneNumber = models.CharField(max_length=20)
class PhoneNumber(forms.Form):
FirstName = forms.CharField(max_length=30)
LastName = forms.CharField(max_length=30)
PhoneNumber = forms.CharField(max_length=20)
I know there is a class for creating a form from the the model, but even there I'm unclear on how the data actually gets to the database. And I'd like to understand the inner workings before I move on to the time-savers. If there is a simple example of how this works in the docs, I've missed it.
Thanks.
UPDATED:
To be clear -- I do know about the ModelForm tool, I'm trying to figure out how to do this without that -- in part so I can better understand what it's doing in the first place.
ANSWERED:
With the help of the anwers, I arrived at this solution:
Form definition:
class ThisForm(forms.Form)
[various Field assignments]
model = ThisModel()
Code in views to save entered data to database:
if request_method == 'POST':
form = ThisForm(request.POST)
if form.is_valid():
for key, value in form.cleaned_data.items():
setattr(form.model, key, value)
form.model.save(form.model)
After this the data entered in the browser form was in the database table.
Note that the call of the model's save() method required passage of the model itself as an argument. I have no idea why.
CAVEAT: I'm a newbie. This succeeded in getting data from a browser to a database table, but God only knows what I've neglected or missed or outright broken along the way. ModelForm definitely seems like a much cleaner solution.
|
[
"Back when I first used Forms and Models (without using ModelForm), what I remember doing was checking if the form was valid, which would set your cleaned data, manually moving the data from the form to the model (or whatever other processing you want to do), and then saving the model. As you can tell, this was extremely tedious when your form exactly (or even closely) matches your model. By using the ModelForm (since you said you weren't quite sure how it worked), when you save the ModelForm, it instantiates an object with the form data according to the model spec and then saves that model for you. So all-in-all, the flow of data goes from the HTML form, to the Django Form, to the Django Model, to the DB.\nSome actual code for your questions:\nTo get the browser form data into the form object:\nif request.method == 'POST':\n form = SomeForm(request.POST)\n if form.is_valid():\n model.attr = form.cleaned_data['attr']\n model.attr2 = form.cleaned_data['attr2']\n model.save()\nelse:\n form = SomeForm()\nreturn render_to_response('page.html', {'form': form, })\n\nIn the template page you can do things like this with the form:\n<form method=\"POST\">\n{{ form.as_p }}\n<input type=\"submit\"/>\n</form>\n\nThat's just one example that I pulled from here.\n",
"I'm not sure which class do you mean. I know that there were a helper, something like form_for_model (don't really remember the exact name; that was way before 1.0 version was released). Right now I'd it that way:\nimport myproject.myapp.models as models\n\nclass PhoneNumberForm(forms.ModelForm):\n class Meta:\n model = models.PhoneNumber\n\nTo see the metaclass magic behind, you'd have to look into the code as there is a lot to explain :]. The constructor of the form can take instance argument. Passing it will make the form operate on an existing record rather than creating a new one. More info here.\n",
"I think ModelForm.save documentation should explain it. With its base class (Form) you would need to use the Form.cleaned_data() to get the field values and set them to appropriate Model fields \"by hand\". ModelForm does all that for you.\n",
"The Django documentation is pretty clear on this subject. However, here is a rough guide for you to get started: You can either override the form's save method or implement that functionality in the view.\nif form.is_valid() # validation - first the fields, then the form itself is validated\n form.save()\n\ninside the form:\ndef save(self, *args, **kwargs):\n foo = Foo()\n foo.somefield = self.cleaned_data['somefield']\n foo.otherfield = self.cleaned_data['otherfield']\n ...\n return foo.save()\n\n"
] |
[
3,
2,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001223763_django_python.txt
|
Q:
Check for a module in Python without using exceptions
I can check for a module in Python doing something like:
try:
import some_module
except ImportError:
print "No some_module!"
But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)
Note: The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions.
A:
It takes trickery to perform the request (and one raise statement is in fact inevitable because it's the one and only way specified in the PEP 302 for an import hook to say "I don't deal with this path item"!), but the following would avoid any try/except:
import sys
sentinel = object()
class FakeLoader(object):
def find_module(self, fullname, path=None):
return self
def load_module(*_):
return sentinel
def fakeHook(apath):
if apath == 'GIVINGUP!!!':
return FakeLoader()
raise ImportError
sys.path.append('GIVINGUP!!!')
sys.path_hooks.append(fakeHook)
def isModuleOK(modulename):
result = __import__(modulename)
return result is not sentinel
print 'sys', isModuleOK('sys')
print 'Cookie', isModuleOK('Cookie')
print 'nonexistent', isModuleOK('nonexistent')
This prints:
sys True
Cookie True
nonexistent False
Of course, these would be absurd lengths to go to in real life for the pointless purpose of avoiding a perfectly normal try/except, but they seem to satisfy the request as posed (and can hopefully prompt Python-wizards wannabes to start their own research -- finding out exactly how and why all of this code does work as required is in fact instructive, which is why for once I'm not offering detailed explanations and URLs;-).
A:
You can read here about how Python locates and imports modules. If you wanted to, you could replicate this logic in python, searching through sys.modules, sys.meta_path & sys.path to look for the required module.
However, predicting whether it would parse successfully (taking into account compiled binary modules) without using exception handling would be very difficult, I imagine!
A:
All methods of importing modules raise exceptions when called. You could try searching the filesystem yourself first for the file, but there are many things to consider.
Not sure why you don't want to use try/except though. It is the best solution, far better than the one I provided. Maybe you should clarify that first, because you probably have an invalid reason for not using try/except.
|
Check for a module in Python without using exceptions
|
I can check for a module in Python doing something like:
try:
import some_module
except ImportError:
print "No some_module!"
But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)
Note: The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions.
|
[
"It takes trickery to perform the request (and one raise statement is in fact inevitable because it's the one and only way specified in the PEP 302 for an import hook to say \"I don't deal with this path item\"!), but the following would avoid any try/except:\nimport sys\n\nsentinel = object()\n\nclass FakeLoader(object):\n def find_module(self, fullname, path=None):\n return self\n def load_module(*_):\n return sentinel\n\ndef fakeHook(apath):\n if apath == 'GIVINGUP!!!':\n return FakeLoader()\n raise ImportError\n\nsys.path.append('GIVINGUP!!!')\nsys.path_hooks.append(fakeHook)\n\ndef isModuleOK(modulename):\n result = __import__(modulename)\n return result is not sentinel\n\nprint 'sys', isModuleOK('sys')\nprint 'Cookie', isModuleOK('Cookie')\nprint 'nonexistent', isModuleOK('nonexistent')\n\nThis prints:\nsys True\nCookie True\nnonexistent False\n\nOf course, these would be absurd lengths to go to in real life for the pointless purpose of avoiding a perfectly normal try/except, but they seem to satisfy the request as posed (and can hopefully prompt Python-wizards wannabes to start their own research -- finding out exactly how and why all of this code does work as required is in fact instructive, which is why for once I'm not offering detailed explanations and URLs;-).\n",
"You can read here about how Python locates and imports modules. If you wanted to, you could replicate this logic in python, searching through sys.modules, sys.meta_path & sys.path to look for the required module.\nHowever, predicting whether it would parse successfully (taking into account compiled binary modules) without using exception handling would be very difficult, I imagine!\n",
"All methods of importing modules raise exceptions when called. You could try searching the filesystem yourself first for the file, but there are many things to consider.\nNot sure why you don't want to use try/except though. It is the best solution, far better than the one I provided. Maybe you should clarify that first, because you probably have an invalid reason for not using try/except.\n"
] |
[
7,
1,
0
] |
[
"sys.modules dictionary seems to contain the info you need.\n"
] |
[
-1
] |
[
"module",
"python",
"python_module"
] |
stackoverflow_0001224585_module_python_python_module.txt
|
Q:
limit downloaded page size
Is there a way to limit amount of data downloaded by python's urllib2 module ? Sometimes I encounter with broken sites with sort of /dev/random as a page and it turns out that they use up all memory on a server.
A:
urllib2.urlopen returns a file-like object, and you can (at least in theory) .read(N) from such an object to limit the amount of data returned to N bytes at most.
This approach is not entirely fool-proof, because an actively-hostile site may go to quite some lengths to fool a reasonably trusty received, like urllib2's default opener; in this case, you'll need to implement and install your own opener that knows how to guard itself against such attacks (for example, getting no more than a MB at a time from the open socket, etc, etc).
|
limit downloaded page size
|
Is there a way to limit amount of data downloaded by python's urllib2 module ? Sometimes I encounter with broken sites with sort of /dev/random as a page and it turns out that they use up all memory on a server.
|
[
"urllib2.urlopen returns a file-like object, and you can (at least in theory) .read(N) from such an object to limit the amount of data returned to N bytes at most.\nThis approach is not entirely fool-proof, because an actively-hostile site may go to quite some lengths to fool a reasonably trusty received, like urllib2's default opener; in this case, you'll need to implement and install your own opener that knows how to guard itself against such attacks (for example, getting no more than a MB at a time from the open socket, etc, etc).\n"
] |
[
3
] |
[] |
[] |
[
"python",
"urllib2"
] |
stackoverflow_0001224910_python_urllib2.txt
|
Q:
Query strange behaviour. Google App Engine datastore
I have a model like this:
class Group(db.Model):
name = db.StringProperty()
description = db.TextProperty()
Sometimes when executing queries like:
groups = Group.all().order("name").fetch(20)
or
groups = Group.all()
I'm getting error massages like this:
Traceback (most recent call last):
File "/opt/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__
handler.get(*groups)
File "/home/al/Desktop/p/mwr-dev/main.py", line 638, in get
groups = Group.all()
AttributeError: type object 'Group' has no attribute 'all'
But when I'm using GQL queries with the same meaning, everything goes fine.
Why does that happens? I'm don't getting why GAE thinks that 'all' is attribute?
UPDATE:
Oops ... I've found out that I also had request handler named the same as model ;(
A:
all is indeed an attribute (specifically an executable one, a method) but as Group inherits from Model it should have that attribute; clearly something strange is going on, for example the name Group at the point does not refer to the object you think it does. I suggest putting a try / except AttributeError, e: around your groups = Group.all() call, and in the except branch emit (e.g. by logging) all possible information you can find about Group, including what __bases__ it actually has, its dir(), and so forth.
This is about how far one can go in trying to help you (diagnosing that something very weird must have happened to the name Group and suggesting how to pinpoint details) without seeing your many hundreds of lines of code that could be doing who-knows-what to that name!-).
|
Query strange behaviour. Google App Engine datastore
|
I have a model like this:
class Group(db.Model):
name = db.StringProperty()
description = db.TextProperty()
Sometimes when executing queries like:
groups = Group.all().order("name").fetch(20)
or
groups = Group.all()
I'm getting error massages like this:
Traceback (most recent call last):
File "/opt/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__
handler.get(*groups)
File "/home/al/Desktop/p/mwr-dev/main.py", line 638, in get
groups = Group.all()
AttributeError: type object 'Group' has no attribute 'all'
But when I'm using GQL queries with the same meaning, everything goes fine.
Why does that happens? I'm don't getting why GAE thinks that 'all' is attribute?
UPDATE:
Oops ... I've found out that I also had request handler named the same as model ;(
|
[
"all is indeed an attribute (specifically an executable one, a method) but as Group inherits from Model it should have that attribute; clearly something strange is going on, for example the name Group at the point does not refer to the object you think it does. I suggest putting a try / except AttributeError, e: around your groups = Group.all() call, and in the except branch emit (e.g. by logging) all possible information you can find about Group, including what __bases__ it actually has, its dir(), and so forth.\nThis is about how far one can go in trying to help you (diagnosing that something very weird must have happened to the name Group and suggesting how to pinpoint details) without seeing your many hundreds of lines of code that could be doing who-knows-what to that name!-).\n"
] |
[
4
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0001224939_google_app_engine_google_cloud_datastore_python.txt
|
Q:
What's the state-of-the-art in Python programming in Windows?
I'm looking to set up my development environment at home for writing Windows applications in Python.
For my first piece, I'm writing a simple, forms-based application that stores data input as XML (and can read that information back.) I do want to set up the tools I'd use professionally, though, having already done a round of didactic programming.
What tools are professional python developers using these days? In order to have a working python environment, what version of the compiler should I be using? What editor is common for professionals? What libraries are considered a must-have for every serious python developer?
Specifically, which Windowing and XML libraries are de rigeur for working in Windows?
A:
I like Eclipse + PyDev (with extensions).
It is available on Windows, and it works very well well. However, there are many other IDEs, with strengths and weakness.
As for the interpreter (Python is interpreted, not compiled!), you have three main choices: CPython, IronPython and Jython.
When people say "Python" they usually refer to "CPython" that is the reference implementation, but the other two (based, respectively, on .Net and Java) are full pythons as well :-)
In your case, I would maybe go on IronPython, because it will allow you to leverage your knowledge of .Net to build the GUI and treating the XML, while leaving the implementation of business logic to Python.
Finally, should you decide to use CPython, finally, there are several choices for working with xml:
minidom; included in the standard library
lxml, faster and with a better API; it means an additional installation on top of Python.
A:
Lots of questions, most hard to answer correctly. First of all, most of python development happens on unix-like platforms. You will hit many walls during development on Windows box.
Python is not a compiled lanugage, current preferred version for production is 2.5. For environement setup you should take a look at virtualenv. Editor is a personal choice, many Python developers use Vim, you can customize it pretty well to suite your needs.
About libraries, Python is very strong around this area and it's really hard to say what is a must to know. If you want to handle XML, I would preffer lxml.
A:
If you go for CPython, make sure you get the win32 extensions by Mark Hammond, either as a separate download which you install on top of the vanilla Python installation, or as part of ActiveState's ActivePython. It includes an integrated editor and debugger.
Jython has recently reached 2.5 compliancy, but we quickly ran into recursion limit issues.
The standard distribution includes IDLE, a graphical editor and debugger.
I like shells, so I'm using IPython for interactive work, and pydb as debugger (unfortunately, I had problems getting pydb to work under Windows).
A:
"What tools are professional python developers using these days?"
Lots
"In order to have a working python environment, what version of the compiler should I be using?"
["compiler" is meaningless. I'll assume you mean "Python"]
We use 2.5.4. We'll be upgrading to 2.6 as soon as we've done the testing.
"What editor is common for professionals?"
We use Komodo Edit.
"What libraries are considered a must-have for every serious python developer?"
We use Django, XLRD, PIL, and a few others. We don't plan this kind of thing in advance. As our requirements arrive, we start looking for libraries. We don't "pre-load" a bunch of "must-have" libraries. The very idea is silly. We load what we need to solve the problems we have.
A:
There are no set standards in these matters, and for good reasons:
there is a fair amount of good choice
different people are productive with different tools
different tools and libraries are suited for solving different problems
That said, I think it's a valid question exactly because there is a fair amount of good choice. When there is too much choice people often do not chose at all and move on. You still need to do your own research to decide what is best for you but you may find here some good starting points.
Here is what I use professionally on windows:
python 2.5.4
latest wxPython
XRC Resource Editor from the wxPython docs & demos for the grunt of the tedious GUI design
lxml or gnosis utils for xml
WingIDE Professional
A:
Taking the headline question literally, the answer has to be IronPython. The 2.0 releases are equivalent to CPython 2.5, and the 2.6 release (currently at beta2) is intended to match CPython 2.6 (full 2.6 release some time in the next couple of months). With either you can use the state of the art in Windows GUI frameworks, i.e. WPF; and you get the whole .net XML support libraries (excepting Linq to XML, which relies on clever bits of C# that IronPython cannot yet emulate).
I've used NetBeans Python plug-in happily as an IDE for IronPython using WPF.
A:
The answer would depend on what you want to do with Python. If you want to do web programming, Python is blessed with many web frameworks. The most popular ones are: Django, Pylons, and Turbogears. There's also Google App Engine, where you can deploy your Python webapp (based on GAE framework) to Google's infrastructure. If you want to do Desktop programming then there is PyQT and TkInter, or you can even try using Java Swing with Jython. And if you want to do Mobile app programming then there is Python for S60 which is backed by Nokia.
Python is interpreted language, so there is no compiler (although the interpreter also compiles your python module into bytecode). I would recommend using Python 2.6 as it has some syntax and libraries that is different compared to 2.5. You can also start learning Python 3.0 too.
There is several IDE that is good for Python. You don't have to get yourself attached into one editor/IDE because most of them are good ones. For the commercial ones there is WingIDE which is really focus on making IDE for Python and I would really recommend IntelliJ IDEA with Python plugin which is really nice if you often look at the libraries in your Python environment. For the free ones (as others have said) there is Komodo Edit or you can also try Netbeans with Python plugin.
As for the must-have libraries, this is depending on what you want to do. What kind of application you want to develop with Python. But I think every Python developer should consider PIL for imaging library. I also use simplejson quite often, because I prefer using JSON rather than XML. If you are using XML though, you can use lxml as it is really fast in parsing XML.
|
What's the state-of-the-art in Python programming in Windows?
|
I'm looking to set up my development environment at home for writing Windows applications in Python.
For my first piece, I'm writing a simple, forms-based application that stores data input as XML (and can read that information back.) I do want to set up the tools I'd use professionally, though, having already done a round of didactic programming.
What tools are professional python developers using these days? In order to have a working python environment, what version of the compiler should I be using? What editor is common for professionals? What libraries are considered a must-have for every serious python developer?
Specifically, which Windowing and XML libraries are de rigeur for working in Windows?
|
[
"I like Eclipse + PyDev (with extensions).\nIt is available on Windows, and it works very well well. However, there are many other IDEs, with strengths and weakness.\nAs for the interpreter (Python is interpreted, not compiled!), you have three main choices: CPython, IronPython and Jython.\nWhen people say \"Python\" they usually refer to \"CPython\" that is the reference implementation, but the other two (based, respectively, on .Net and Java) are full pythons as well :-)\nIn your case, I would maybe go on IronPython, because it will allow you to leverage your knowledge of .Net to build the GUI and treating the XML, while leaving the implementation of business logic to Python.\nFinally, should you decide to use CPython, finally, there are several choices for working with xml:\n\nminidom; included in the standard library\nlxml, faster and with a better API; it means an additional installation on top of Python.\n\n",
"Lots of questions, most hard to answer correctly. First of all, most of python development happens on unix-like platforms. You will hit many walls during development on Windows box.\nPython is not a compiled lanugage, current preferred version for production is 2.5. For environement setup you should take a look at virtualenv. Editor is a personal choice, many Python developers use Vim, you can customize it pretty well to suite your needs.\nAbout libraries, Python is very strong around this area and it's really hard to say what is a must to know. If you want to handle XML, I would preffer lxml.\n",
"\nIf you go for CPython, make sure you get the win32 extensions by Mark Hammond, either as a separate download which you install on top of the vanilla Python installation, or as part of ActiveState's ActivePython. It includes an integrated editor and debugger.\nJython has recently reached 2.5 compliancy, but we quickly ran into recursion limit issues.\nThe standard distribution includes IDLE, a graphical editor and debugger.\nI like shells, so I'm using IPython for interactive work, and pydb as debugger (unfortunately, I had problems getting pydb to work under Windows).\n\n",
"\"What tools are professional python developers using these days?\"\nLots\n\"In order to have a working python environment, what version of the compiler should I be using?\"\n[\"compiler\" is meaningless. I'll assume you mean \"Python\"]\nWe use 2.5.4. We'll be upgrading to 2.6 as soon as we've done the testing.\n\"What editor is common for professionals?\"\nWe use Komodo Edit.\n\"What libraries are considered a must-have for every serious python developer?\"\nWe use Django, XLRD, PIL, and a few others. We don't plan this kind of thing in advance. As our requirements arrive, we start looking for libraries. We don't \"pre-load\" a bunch of \"must-have\" libraries. The very idea is silly. We load what we need to solve the problems we have. \n",
"There are no set standards in these matters, and for good reasons:\n\nthere is a fair amount of good choice\ndifferent people are productive with different tools\ndifferent tools and libraries are suited for solving different problems\n\nThat said, I think it's a valid question exactly because there is a fair amount of good choice. When there is too much choice people often do not chose at all and move on. You still need to do your own research to decide what is best for you but you may find here some good starting points.\nHere is what I use professionally on windows:\n\npython 2.5.4\nlatest wxPython\nXRC Resource Editor from the wxPython docs & demos for the grunt of the tedious GUI design\nlxml or gnosis utils for xml\nWingIDE Professional\n\n",
"Taking the headline question literally, the answer has to be IronPython. The 2.0 releases are equivalent to CPython 2.5, and the 2.6 release (currently at beta2) is intended to match CPython 2.6 (full 2.6 release some time in the next couple of months). With either you can use the state of the art in Windows GUI frameworks, i.e. WPF; and you get the whole .net XML support libraries (excepting Linq to XML, which relies on clever bits of C# that IronPython cannot yet emulate).\nI've used NetBeans Python plug-in happily as an IDE for IronPython using WPF.\n",
"The answer would depend on what you want to do with Python. If you want to do web programming, Python is blessed with many web frameworks. The most popular ones are: Django, Pylons, and Turbogears. There's also Google App Engine, where you can deploy your Python webapp (based on GAE framework) to Google's infrastructure. If you want to do Desktop programming then there is PyQT and TkInter, or you can even try using Java Swing with Jython. And if you want to do Mobile app programming then there is Python for S60 which is backed by Nokia.\nPython is interpreted language, so there is no compiler (although the interpreter also compiles your python module into bytecode). I would recommend using Python 2.6 as it has some syntax and libraries that is different compared to 2.5. You can also start learning Python 3.0 too.\nThere is several IDE that is good for Python. You don't have to get yourself attached into one editor/IDE because most of them are good ones. For the commercial ones there is WingIDE which is really focus on making IDE for Python and I would really recommend IntelliJ IDEA with Python plugin which is really nice if you often look at the libraries in your Python environment. For the free ones (as others have said) there is Komodo Edit or you can also try Netbeans with Python plugin.\nAs for the must-have libraries, this is depending on what you want to do. What kind of application you want to develop with Python. But I think every Python developer should consider PIL for imaging library. I also use simplejson quite often, because I prefer using JSON rather than XML. If you are using XML though, you can use lxml as it is really fast in parsing XML.\n"
] |
[
7,
2,
2,
1,
1,
1,
1
] |
[] |
[] |
[
"ide",
"python",
"windows",
"wxpython",
"xml"
] |
stackoverflow_0001224567_ide_python_windows_wxpython_xml.txt
|
Q:
How to stop WSGI from hanging apache
I have django running through WSGI like this :
<VirtualHost *:80>
WSGIScriptAlias / /home/ptarjan/django/django.wsgi
WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup ptarjan
Alias /media /home/ptarjan/django/mysite/media/
</VirtualHost>
But if in python I do :
def handler(request) :
data = urllib2.urlopen("http://example.com/really/unresponsive/url").read()
the whole apache server hangs and is unresponsive with this backtrace
#0 0x00007ffe3602a570 in __read_nocancel () from /lib/libpthread.so.0
#1 0x00007ffe36251d1c in apr_file_read () from /usr/lib/libapr-1.so.0
#2 0x00007ffe364778b5 in ?? () from /usr/lib/libaprutil-1.so.0
#3 0x0000000000440ec2 in ?? ()
#4 0x00000000004412ae in ap_scan_script_header_err_core ()
#5 0x00007ffe2a2fe512 in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#6 0x00007ffe2a2f9bdd in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#7 0x000000000043b623 in ap_run_handler ()
#8 0x000000000043eb4f in ap_invoke_handler ()
#9 0x000000000044bbd8 in ap_process_request ()
#10 0x0000000000448cd8 in ?? ()
#11 0x0000000000442a13 in ap_run_process_connection ()
#12 0x000000000045017d in ?? ()
#13 0x00000000004504d4 in ?? ()
#14 0x00000000004510f6 in ap_mpm_run ()
#15 0x0000000000428425 in main ()
on Debian Apache 2.2.11-7.
Similarly, can we be protected against :
def handler(request) :
while (1) :
pass
In PHP, I would set time and memory limits.
A:
It is not 'deadlock-timeout' you want as specified by another, that is for a very special purpose which will not help in this case.
As far as trying to use mod_wsgi features, you instead want the 'inactivity-timeout' option for WSGIDaemonProcess directive.
Even then, this is not a complete solution. This is because the 'inactivity-timeout' option is specifically to detect whether all request processing by a daemon process has ceased, it is not a per request timeout. It only equates to a per request timeout if daemon processes are single threaded. As well as help to unstick a process, the option will also have side effect of restarting daemon process if no requests arrive at all in that time.
In short, there is no way at mod_wsgi level to have per request timeouts, this is because there is no real way of interrupting a request, or thread, in Python.
What you really need to implement is a timeout on the HTTP request in your application code. Am not sure where it is up to and whether available already, but do a Google search for 'urllib2 socket timeout'.
A:
If I understand well the question, you want to protect apache from locking up when running some random scripts from people. Well, if you're running untrusted code, I think you have other things to worry about that are worst than apache.
That said, you can use some configuration directives to adjust a safer environment. These two below are very useful:
WSGIApplicationGroup - Sets which application group WSGI application belongs to. It allows to separate settings for each user - All WSGI applications within the same application group will execute within the context of the same Python sub interpreter of the process handling the request.
WSGIDaemonProcess - Configures a distinct daemon process for running applications. The daemon processes can be run as a user different to that which the Apache child processes would normally be run as. This directive accepts a lot of useful options, I'll list some of them:
user=name | user=#uid, group=name | group=#gid:
Defines the UNIX user and groupname name or numeric user uid or group gid of the user/group that the daemon processes should be run as.
stack-size=nnn
The amount of virtual memory in bytes to be allocated for the stack corresponding to each thread created by mod_wsgi in a daemon process.
deadlock-timeout=sss
Defines the maximum number of seconds allowed to pass before the daemon process is shutdown and restarted after a potential deadlock on the Python GIL has been detected. The default is 300 seconds.
You can read more about the configuration directives here.
|
How to stop WSGI from hanging apache
|
I have django running through WSGI like this :
<VirtualHost *:80>
WSGIScriptAlias / /home/ptarjan/django/django.wsgi
WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup ptarjan
Alias /media /home/ptarjan/django/mysite/media/
</VirtualHost>
But if in python I do :
def handler(request) :
data = urllib2.urlopen("http://example.com/really/unresponsive/url").read()
the whole apache server hangs and is unresponsive with this backtrace
#0 0x00007ffe3602a570 in __read_nocancel () from /lib/libpthread.so.0
#1 0x00007ffe36251d1c in apr_file_read () from /usr/lib/libapr-1.so.0
#2 0x00007ffe364778b5 in ?? () from /usr/lib/libaprutil-1.so.0
#3 0x0000000000440ec2 in ?? ()
#4 0x00000000004412ae in ap_scan_script_header_err_core ()
#5 0x00007ffe2a2fe512 in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#6 0x00007ffe2a2f9bdd in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#7 0x000000000043b623 in ap_run_handler ()
#8 0x000000000043eb4f in ap_invoke_handler ()
#9 0x000000000044bbd8 in ap_process_request ()
#10 0x0000000000448cd8 in ?? ()
#11 0x0000000000442a13 in ap_run_process_connection ()
#12 0x000000000045017d in ?? ()
#13 0x00000000004504d4 in ?? ()
#14 0x00000000004510f6 in ap_mpm_run ()
#15 0x0000000000428425 in main ()
on Debian Apache 2.2.11-7.
Similarly, can we be protected against :
def handler(request) :
while (1) :
pass
In PHP, I would set time and memory limits.
|
[
"It is not 'deadlock-timeout' you want as specified by another, that is for a very special purpose which will not help in this case.\nAs far as trying to use mod_wsgi features, you instead want the 'inactivity-timeout' option for WSGIDaemonProcess directive.\nEven then, this is not a complete solution. This is because the 'inactivity-timeout' option is specifically to detect whether all request processing by a daemon process has ceased, it is not a per request timeout. It only equates to a per request timeout if daemon processes are single threaded. As well as help to unstick a process, the option will also have side effect of restarting daemon process if no requests arrive at all in that time.\nIn short, there is no way at mod_wsgi level to have per request timeouts, this is because there is no real way of interrupting a request, or thread, in Python.\nWhat you really need to implement is a timeout on the HTTP request in your application code. Am not sure where it is up to and whether available already, but do a Google search for 'urllib2 socket timeout'.\n",
"If I understand well the question, you want to protect apache from locking up when running some random scripts from people. Well, if you're running untrusted code, I think you have other things to worry about that are worst than apache.\nThat said, you can use some configuration directives to adjust a safer environment. These two below are very useful:\n\nWSGIApplicationGroup - Sets which application group WSGI application belongs to. It allows to separate settings for each user - All WSGI applications within the same application group will execute within the context of the same Python sub interpreter of the process handling the request.\nWSGIDaemonProcess - Configures a distinct daemon process for running applications. The daemon processes can be run as a user different to that which the Apache child processes would normally be run as. This directive accepts a lot of useful options, I'll list some of them:\n\nuser=name | user=#uid, group=name | group=#gid:\nDefines the UNIX user and groupname name or numeric user uid or group gid of the user/group that the daemon processes should be run as.\nstack-size=nnn\nThe amount of virtual memory in bytes to be allocated for the stack corresponding to each thread created by mod_wsgi in a daemon process. \ndeadlock-timeout=sss\nDefines the maximum number of seconds allowed to pass before the daemon process is shutdown and restarted after a potential deadlock on the Python GIL has been detected. The default is 300 seconds. \n\n\nYou can read more about the configuration directives here.\n"
] |
[
13,
3
] |
[] |
[] |
[
"apache",
"django",
"mod_wsgi",
"python"
] |
stackoverflow_0001223927_apache_django_mod_wsgi_python.txt
|
Q:
wxPython menu doesn't display image
I am creating a menu and assigning images to menu items, sometime first item in menu doesn't display any image, I am not able to find the reason. I have tried to make a simple stand alone example and below is the code which does demonstrates the problem on my machine.
I am using windows XP, wx 2.8.7.1 (msw-unicode)'
import wx
def getBmp():
bmp = wx.EmptyBitmap(16,16)
return bmp
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, style=wx.DEFAULT_FRAME_STYLE, parent=None)
self.SetTitle("why New has no image?")
menuBar = wx.MenuBar()
fileMenu=wx.Menu()
item = fileMenu.Append(wx.ID_NEW, "New")
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_OPEN, "Open")
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_SAVE, "Save")
item.SetBitmap(getBmp())
menuBar.Append(fileMenu, "File")
self.SetMenuBar(menuBar)
app = wx.PySimpleApp()
frame=MyFrame()
frame.Show()
app.SetTopWindow(frame)
app.MainLoop()
So are you able to see the problem and what could be the reason for it?
Conclusion: Yes this is a official bug, I have created a simple Menu class to overcome this bug, using the trick given by "balpha" in selected answer
It overrides each menu.Append method and sees if menu item with image is being added for first time, if yes creates a dummy item and deletes it later.
This also adds feature/constraint so that instead of calling SetBitmap, you should pass bitmap as optional argument image
import wx
class MockMenu(wx.Menu):
"""
A custom menu class in which image param can be passed to each Append method
it also takes care of bug http://trac.wxwidgets.org/ticket/4011
"""
def __init__(self, *args, **kwargs):
wx.Menu.__init__(self, *args, **kwargs)
self._count = 0
def applyBmp(self, unboundMethod, *args, **kwargs):
"""
there is a bug in wxPython so that it will not display first item bitmap
http://trac.wxwidgets.org/ticket/4011
so we keep track and add a dummy before it and delete it after words
may not work if menu has only one item
"""
bmp = None
if 'image' in kwargs:
bmp = kwargs['image']
tempitem = None
# add temp item so it is first item with bmp
if bmp and self._count == 1:
tempitem = wx.Menu.Append(self, -1,"HACK")
tempitem.SetBitmap(bmp)
ret = unboundMethod(self, *args, **kwargs)
if bmp:
ret.SetBitmap(bmp)
# delete temp item
if tempitem is not None:
self.Remove(tempitem.GetId())
self._lastRet = ret
return ret
def Append(self, *args, **kwargs):
return self.applyBmp(wx.Menu.Append, *args, **kwargs)
def AppendCheckItem(self, *args, **kwargs):
return self.applyBmp(wx.Menu.AppendCheckItem, *args, **kwargs)
def AppendMenu(self, *args, **kwargs):
return self.applyBmp(wx.Menu.AppendMenu, *args, **kwargs)
A:
This hack does not appear to be necessary if you create each menu item with wx.MenuItem(), set its bitmap, and only then append it to the menu. This causes the bitmaps to show up correctly. I'm testing with wxPython 2.8.10.1 on Windows.
A:
This is a confirmed bug which appearently has been open for quite a while. After trying around a little bit, this workaround seems to do it:
menuBar = wx.MenuBar()
fileMenu=wx.Menu()
tempitem = fileMenu.Append(-1,"X") # !!!
tempitem.SetBitmap(getBmp()) # !!!
item = fileMenu.Append(wx.ID_NEW, "New")
fileMenu.Remove(tempitem.GetId()) # !!!
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_OPEN, "Open")
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_SAVE, "Save")
item.SetBitmap(getBmp())
menuBar.Append(fileMenu, "File")
self.SetMenuBar(menuBar)
Note that the position of the fileMenu.Remove call is the earliest position that works, but you can also move it to the bottom. HTH.
|
wxPython menu doesn't display image
|
I am creating a menu and assigning images to menu items, sometime first item in menu doesn't display any image, I am not able to find the reason. I have tried to make a simple stand alone example and below is the code which does demonstrates the problem on my machine.
I am using windows XP, wx 2.8.7.1 (msw-unicode)'
import wx
def getBmp():
bmp = wx.EmptyBitmap(16,16)
return bmp
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, style=wx.DEFAULT_FRAME_STYLE, parent=None)
self.SetTitle("why New has no image?")
menuBar = wx.MenuBar()
fileMenu=wx.Menu()
item = fileMenu.Append(wx.ID_NEW, "New")
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_OPEN, "Open")
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_SAVE, "Save")
item.SetBitmap(getBmp())
menuBar.Append(fileMenu, "File")
self.SetMenuBar(menuBar)
app = wx.PySimpleApp()
frame=MyFrame()
frame.Show()
app.SetTopWindow(frame)
app.MainLoop()
So are you able to see the problem and what could be the reason for it?
Conclusion: Yes this is a official bug, I have created a simple Menu class to overcome this bug, using the trick given by "balpha" in selected answer
It overrides each menu.Append method and sees if menu item with image is being added for first time, if yes creates a dummy item and deletes it later.
This also adds feature/constraint so that instead of calling SetBitmap, you should pass bitmap as optional argument image
import wx
class MockMenu(wx.Menu):
"""
A custom menu class in which image param can be passed to each Append method
it also takes care of bug http://trac.wxwidgets.org/ticket/4011
"""
def __init__(self, *args, **kwargs):
wx.Menu.__init__(self, *args, **kwargs)
self._count = 0
def applyBmp(self, unboundMethod, *args, **kwargs):
"""
there is a bug in wxPython so that it will not display first item bitmap
http://trac.wxwidgets.org/ticket/4011
so we keep track and add a dummy before it and delete it after words
may not work if menu has only one item
"""
bmp = None
if 'image' in kwargs:
bmp = kwargs['image']
tempitem = None
# add temp item so it is first item with bmp
if bmp and self._count == 1:
tempitem = wx.Menu.Append(self, -1,"HACK")
tempitem.SetBitmap(bmp)
ret = unboundMethod(self, *args, **kwargs)
if bmp:
ret.SetBitmap(bmp)
# delete temp item
if tempitem is not None:
self.Remove(tempitem.GetId())
self._lastRet = ret
return ret
def Append(self, *args, **kwargs):
return self.applyBmp(wx.Menu.Append, *args, **kwargs)
def AppendCheckItem(self, *args, **kwargs):
return self.applyBmp(wx.Menu.AppendCheckItem, *args, **kwargs)
def AppendMenu(self, *args, **kwargs):
return self.applyBmp(wx.Menu.AppendMenu, *args, **kwargs)
|
[
"This hack does not appear to be necessary if you create each menu item with wx.MenuItem(), set its bitmap, and only then append it to the menu. This causes the bitmaps to show up correctly. I'm testing with wxPython 2.8.10.1 on Windows.\n",
"This is a confirmed bug which appearently has been open for quite a while. After trying around a little bit, this workaround seems to do it:\n menuBar = wx.MenuBar()\n fileMenu=wx.Menu()\n tempitem = fileMenu.Append(-1,\"X\") # !!!\n tempitem.SetBitmap(getBmp()) # !!!\n item = fileMenu.Append(wx.ID_NEW, \"New\")\n fileMenu.Remove(tempitem.GetId()) # !!!\n item.SetBitmap(getBmp())\n item = fileMenu.Append(wx.ID_OPEN, \"Open\")\n item.SetBitmap(getBmp())\n item = fileMenu.Append(wx.ID_SAVE, \"Save\")\n item.SetBitmap(getBmp())\n menuBar.Append(fileMenu, \"File\")\n self.SetMenuBar(menuBar) \n\nNote that the position of the fileMenu.Remove call is the earliest position that works, but you can also move it to the bottom. HTH.\n"
] |
[
4,
2
] |
[] |
[] |
[
"menu",
"python",
"wxpython"
] |
stackoverflow_0001078661_menu_python_wxpython.txt
|
Q:
How can I merge fields in a CSV string using Python?
I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:
,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.
Thanks.
A:
Something like this?
import csv
source= csv.reader( open("some file","rb") )
dest= csv.writer( open("another file","wb") )
for row in source:
result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
dest.writerow( result )
Example
>>> data=''',,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
... '''.splitlines()
>>> rdr= csv.reader( data )
>>> row= rdr.next()
>>> row
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CT', '', 'goo', '' ]
>>> row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CTgoo', '']
A:
You can use the csv module to do the heavy lifting: http://docs.python.org/library/csv.html
You didn't say exactly how you wanted to merge the columns; presumably you don't want your merged field to be "Moved from Portland, CTgoo". The code below allows you to specify a separator string (maybe ", ") and handles empty/blank fields.
[transcript of session]
prompt>type merge.py
import csv
def merge_csv_cols(infile, outfile, startcol, numcols, sep=", "):
reader = csv.reader(open(infile, "rb"))
writer = csv.writer(open(outfile, "wb"))
endcol = startcol + numcols
for row in reader:
merged = sep.join(x for x in row[startcol:endcol] if x.strip())
row[startcol:endcol] = [merged]
writer.writerow(row)
if __name__ == "__main__":
import sys
args = sys.argv[1:6]
args[2:4] = map(int, args[2:4])
merge_csv_cols(*args)
prompt>type input.csv
1,2,3,4,5,6,7,8,9,a,b,c
1,2,3,4,5,6,,,,a,b,c
1,2,3,4,5,6,7,8,,a,b,c
1,2,3,4,5,6,7,,9,a,b,c
prompt>\python26\python merge.py input.csv output.csv 6 3 ", "
prompt>type output.csv
1,2,3,4,5,6,"7, 8, 9",a,b,c
1,2,3,4,5,6,,a,b,c
1,2,3,4,5,6,"7, 8",a,b,c
1,2,3,4,5,6,"7, 9",a,b,c
A:
There's a builtin module in Python for parsing CSV files:
http://docs.python.org/library/csv.html
A:
You have tagged this question as 'database'. In fact, maybe it would be easier to upload the two files to separate tables of the db (you can use sqllite or any python sql library, like sqlalchemy) and then join them.
That would give you some advantage after, you would be able to use a sql syntax to query the tables and you can store it on the disk instead of keeping it on memory, so think about it.. :)
|
How can I merge fields in a CSV string using Python?
|
I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:
,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.
Thanks.
|
[
"Something like this?\nimport csv\nsource= csv.reader( open(\"some file\",\"rb\") )\ndest= csv.writer( open(\"another file\",\"wb\") )\nfor row in source:\n result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]\n dest.writerow( result )\n\n\nExample\n>>> data=''',,Joe,Smith,New Haven,CT,\"Moved from Portland, CT\",,goo,\n... '''.splitlines()\n>>> rdr= csv.reader( data )\n>>> row= rdr.next()\n>>> row\n['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CT', '', 'goo', '' ]\n>>> row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]\n['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CTgoo', '']\n\n",
"You can use the csv module to do the heavy lifting: http://docs.python.org/library/csv.html\nYou didn't say exactly how you wanted to merge the columns; presumably you don't want your merged field to be \"Moved from Portland, CTgoo\". The code below allows you to specify a separator string (maybe \", \") and handles empty/blank fields.\n[transcript of session]\nprompt>type merge.py\nimport csv\n\ndef merge_csv_cols(infile, outfile, startcol, numcols, sep=\", \"):\n reader = csv.reader(open(infile, \"rb\"))\n writer = csv.writer(open(outfile, \"wb\"))\n endcol = startcol + numcols\n for row in reader:\n merged = sep.join(x for x in row[startcol:endcol] if x.strip())\n row[startcol:endcol] = [merged]\n writer.writerow(row)\n\nif __name__ == \"__main__\":\n import sys\n args = sys.argv[1:6]\n args[2:4] = map(int, args[2:4])\n merge_csv_cols(*args)\n\nprompt>type input.csv\n1,2,3,4,5,6,7,8,9,a,b,c\n1,2,3,4,5,6,,,,a,b,c\n1,2,3,4,5,6,7,8,,a,b,c\n1,2,3,4,5,6,7,,9,a,b,c\n\nprompt>\\python26\\python merge.py input.csv output.csv 6 3 \", \"\n\nprompt>type output.csv\n1,2,3,4,5,6,\"7, 8, 9\",a,b,c\n1,2,3,4,5,6,,a,b,c\n1,2,3,4,5,6,\"7, 8\",a,b,c\n1,2,3,4,5,6,\"7, 9\",a,b,c\n\n",
"There's a builtin module in Python for parsing CSV files:\nhttp://docs.python.org/library/csv.html\n",
"You have tagged this question as 'database'. In fact, maybe it would be easier to upload the two files to separate tables of the db (you can use sqllite or any python sql library, like sqlalchemy) and then join them.\nThat would give you some advantage after, you would be able to use a sql syntax to query the tables and you can store it on the disk instead of keeping it on memory, so think about it.. :)\n"
] |
[
10,
3,
1,
1
] |
[] |
[] |
[
"csv",
"database",
"python",
"string"
] |
stackoverflow_0001223967_csv_database_python_string.txt
|
Q:
Python: How to import part of a namespace
I have a structure such this works :
import a.b.c
a.b.c.foo()
and this also works :
from a.b import c
c.foo()
but this doesn't work :
from a import b.c
b.c.foo()
nor does :
from a import b
b.c.foo()
How can I do the import so that b.c.foo() works?
A:
Just rename it:
from a.b import c as BAR
BAR.foo()
A:
In your 'b' package, you need to add 'import c' so that it is always accessible as part of b.
A:
from a import b
from a.b import c
b.c = c
A:
import a.b.c
from a import b
b.c.foo()
The order of the import statements doesn't matter.
|
Python: How to import part of a namespace
|
I have a structure such this works :
import a.b.c
a.b.c.foo()
and this also works :
from a.b import c
c.foo()
but this doesn't work :
from a import b.c
b.c.foo()
nor does :
from a import b
b.c.foo()
How can I do the import so that b.c.foo() works?
|
[
"Just rename it:\n\nfrom a.b import c as BAR\n\nBAR.foo()\n\n",
"In your 'b' package, you need to add 'import c' so that it is always accessible as part of b.\n",
"from a import b\nfrom a.b import c\nb.c = c\n\n",
"import a.b.c\nfrom a import b\nb.c.foo()\n\nThe order of the import statements doesn't matter.\n"
] |
[
9,
2,
2,
0
] |
[] |
[] |
[
"import",
"namespaces",
"python"
] |
stackoverflow_0001225481_import_namespaces_python.txt
|
Q:
Error starting Django with Pinax
Upon trying to start a Pinax app, I receive the following error:
Error: No module named notification
Below are the steps I took
svn co http://svn.pinaxproject.com/pinax/trunk/ pinax
cd pinax/pinax/projects/basic_project
./manage.py syncdb
Any suggestions?
UPDATE:
Turns out there are some bugs in the SVN version. Downloading the latest release solved my problem. If any one has any other suggestions on getting the trunk working, they would still be appreciated.
A:
I'd avoid the svn version all together. It's unmaintained and out of date. Instead, use the git version at http://github.com/pinax/pinax or (even better) the recently release 0.7b3 downloadable from http://pinaxproject.com
A:
Two thoughts:
1. Check all of your imports to make sure that notification is getting into the namespace.
2. You may be missing quotes around an import path (eg. in your urls.py: (r'^test', 'mysite.notification') -- sometimes I forget the quotes around the view)
A:
Try following the latest install instructions here:
http://github.com/pinax/pinax/blob/600d6c5ca0b45814bdc73b1264d28bb66c661ac8/INSTALL
Don't think this will work on Windows (maybe if you are using cygwin) as they are using virtualenv and pip.
Note the version has recently been upgraded to 0.7rc1
IIRC I had to add a directory or two to the Python path last time I did a fresh install of Pinax. I'm doing a fresh checkout now into a new virtualenv, I'll edit this answer if I hit any snags.
|
Error starting Django with Pinax
|
Upon trying to start a Pinax app, I receive the following error:
Error: No module named notification
Below are the steps I took
svn co http://svn.pinaxproject.com/pinax/trunk/ pinax
cd pinax/pinax/projects/basic_project
./manage.py syncdb
Any suggestions?
UPDATE:
Turns out there are some bugs in the SVN version. Downloading the latest release solved my problem. If any one has any other suggestions on getting the trunk working, they would still be appreciated.
|
[
"I'd avoid the svn version all together. It's unmaintained and out of date. Instead, use the git version at http://github.com/pinax/pinax or (even better) the recently release 0.7b3 downloadable from http://pinaxproject.com\n",
"Two thoughts:\n1. Check all of your imports to make sure that notification is getting into the namespace.\n2. You may be missing quotes around an import path (eg. in your urls.py: (r'^test', 'mysite.notification') -- sometimes I forget the quotes around the view)\n",
"Try following the latest install instructions here:\nhttp://github.com/pinax/pinax/blob/600d6c5ca0b45814bdc73b1264d28bb66c661ac8/INSTALL\nDon't think this will work on Windows (maybe if you are using cygwin) as they are using virtualenv and pip.\nNote the version has recently been upgraded to 0.7rc1\nIIRC I had to add a directory or two to the Python path last time I did a fresh install of Pinax. I'm doing a fresh checkout now into a new virtualenv, I'll edit this answer if I hit any snags.\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"django",
"pinax",
"python"
] |
stackoverflow_0001223513_django_pinax_python.txt
|
Q:
Problem running functions from a DLL file using ctypes in Object-oriented Python
I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program.
However I've encoutered some problems with one specific instrument when I'm trying to call functions that I've "masked" out from the instruments DLL file.
When I use the interactive python shell it works perfectly (although its alot of word clobbering). But when I implement the functions in a object-oriented manner the program fails, well actually it doesn't fail it just doesn't do anything. This is the first method that's called: (ctypes and ctypes.util is imported)
def init_hardware(self):
""" Inits the instrument """
self.write_log("Initialising the automatic tuner")
version_string = create_string_buffer(80)
self.error_string = create_string_buffer(80)
self.name = "Maury MT982EU"
self.write_log("Tuner DLL path: %s", find_library('MLibTuners'))
self.maury = WinDLL('MlibTuners')
self.maury.get_tuner_driver_version(version_string)
if (version_string.value == ""):
self.write_log("IMPORTANT: Error obtaining the driver version")
else:
self.write_log("Version number of the DLL: %s" % version_string.value)
self.ThreeTypeLong = c_long * 3
Now that works swell, everything is perfect and I get perfect log-entries.
But when I try to run a method further into the program called:
def add_tuner_and_controller(self, name, serial_number, tuner_number=0):
""" Adds the tuner to the driver object, controller is inside the tuner """
self.write_log("Adding tuner %d and the built-in controller" % tuner_number)
TempType = self.ThreeTypeLong()
self.maury.add_controller(c_short(tuner_number), c_char_p(self.file_path), c_char_p(name), c_int(0), c_int(0),
c_long(0), c_short(serial_number), self.error_string)
self.maury.add_tuner(c_short(tuner_number), c_char_p(name), c_short(serial_number), c_short(0),
c_short(1), pointer(c_double()), TempType, pointer(c_double()), pointer(c_double()),
pointer(c_double()), self.error_string)
The program suddenly stops working/keeps running , nothing happenes when the "self.maury"-line is called. When I place everything in the init_hardware method it works perfectly so I'm guessing there's a slight memory "error" or something with the objective oriented structure. I really want it to remain this way, is there anyway to isolate the functions in this manner? or do I have to restrict myself to a big chunk of code?
EDIT:
Documentation info:
[Legend: The stars indicate pointers and the brackets indicate arrays]
The add_tuner function adds or updates one tuner in the tuner driver object.
short add_tuner(short tuner_number, char model[ ], short serial_number, short ctlr_num, short ctlr_port, short *no_of_motors, long max_range[ ], double *fmin, double *fmax, double *fcrossover, char error_string[ ])
Output: no_motors, max_range (array of three numbers), fmin, fmax, fcrossover,error_string (80+ characters long), function-return->Error flag
The add_controller function adds or updates one controller in the tuner driver object
short add_controller(short controller_number, char driver[ ], char model[ ], int timeout, int address, long delay_ms, char error_string[ ])
Output: error_string, function-return->Error flag
A:
I'm not sure about your exact problem, but here's a couple general tips:
For those functions that you are calling outside of the constructor, I would strongly recommend setting their argtypes in the constructor as well. Once you've declared the argtypes, you shouldn't need to cast all the arguments as c_short, c_double, etc. Moreover, if you do accidentally pass an incorrect argument to a C function, Python will raise a runtime error instead of crashing within the DLL.
Another minor detail, but you should be using x = 0; byref(x) or maybe POINTER(c_double)() instead of pointer(c_double()) in the tuner and controller.
I've been writing some ctypes classes in Python 2.6 recently as well, and I haven't seen any issues like what you're describing. Since there apparently aren't any Python bug reports on that either, I strongly believe that there's just a minute detail that we are both overlooking in your method that is having a problem.
A:
Are any of the parameters in add-controller or add-tuner actually return values?
Strongly recommend that you define prototypes of your functions, rather than calling them direct with casts of all the parameters.
I'm sure you've read this page already, but the section you want to look at is Function Prototypes. Makes the code much cleaner and easier to trace/debug.
Also -- as Mark Rushakoff mentions too -- using pointer(c_double()) and like in your call is pretty icky. I have much better luck w/ POINTER(), and recommend again that you predeclare the value as a variable, and pass the variable in your function call. Then at least you can examine its value afterward for strange behavior.
EDIT: So your prototype and call will look something like this:
prototype = WINFUNCTYPE(
c_int, # Return value (correct? Guess)
c_short, # tuner_number
c_char_p, # file_path
c_char_p, # name
c_int, # 0?
c_int, # 0?
c_long, # 0?
c_short, # serial_number
c_char_p, # error_string
)
# 1 input, 2 output, 4 input default to zero (I think; check doc page)
paramflags = (1, 'TunerNumber' ), (1, 'FilePath' ), (1, 'Name' ), ...
AddController = prototype(('add_controller', WinDLL.MlibTuners), paramflags)
Then your call is much cleaner:
arg1 = 0
arg2 = 0
arg3 = 0
AddController(tuner_number, self.file_path, name, arg1, arg2, arg3,
serial_number, self.error_string)
A:
I found out that the only way to call the functions in the exported DLL was to use the DLL through a parameter in each method. (the program exports the dll and in each method called it will send it as a parameter).
It looks pretty ugly but that's the only way I found to be working for me. I even tried exporting the DLL as an class attribute. The system I'm working with is pretty hefty so I guess there is some boboo-code somewhere that makes it fail. Thanks for all the feedback and tips!
/Mazdak
|
Problem running functions from a DLL file using ctypes in Object-oriented Python
|
I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program.
However I've encoutered some problems with one specific instrument when I'm trying to call functions that I've "masked" out from the instruments DLL file.
When I use the interactive python shell it works perfectly (although its alot of word clobbering). But when I implement the functions in a object-oriented manner the program fails, well actually it doesn't fail it just doesn't do anything. This is the first method that's called: (ctypes and ctypes.util is imported)
def init_hardware(self):
""" Inits the instrument """
self.write_log("Initialising the automatic tuner")
version_string = create_string_buffer(80)
self.error_string = create_string_buffer(80)
self.name = "Maury MT982EU"
self.write_log("Tuner DLL path: %s", find_library('MLibTuners'))
self.maury = WinDLL('MlibTuners')
self.maury.get_tuner_driver_version(version_string)
if (version_string.value == ""):
self.write_log("IMPORTANT: Error obtaining the driver version")
else:
self.write_log("Version number of the DLL: %s" % version_string.value)
self.ThreeTypeLong = c_long * 3
Now that works swell, everything is perfect and I get perfect log-entries.
But when I try to run a method further into the program called:
def add_tuner_and_controller(self, name, serial_number, tuner_number=0):
""" Adds the tuner to the driver object, controller is inside the tuner """
self.write_log("Adding tuner %d and the built-in controller" % tuner_number)
TempType = self.ThreeTypeLong()
self.maury.add_controller(c_short(tuner_number), c_char_p(self.file_path), c_char_p(name), c_int(0), c_int(0),
c_long(0), c_short(serial_number), self.error_string)
self.maury.add_tuner(c_short(tuner_number), c_char_p(name), c_short(serial_number), c_short(0),
c_short(1), pointer(c_double()), TempType, pointer(c_double()), pointer(c_double()),
pointer(c_double()), self.error_string)
The program suddenly stops working/keeps running , nothing happenes when the "self.maury"-line is called. When I place everything in the init_hardware method it works perfectly so I'm guessing there's a slight memory "error" or something with the objective oriented structure. I really want it to remain this way, is there anyway to isolate the functions in this manner? or do I have to restrict myself to a big chunk of code?
EDIT:
Documentation info:
[Legend: The stars indicate pointers and the brackets indicate arrays]
The add_tuner function adds or updates one tuner in the tuner driver object.
short add_tuner(short tuner_number, char model[ ], short serial_number, short ctlr_num, short ctlr_port, short *no_of_motors, long max_range[ ], double *fmin, double *fmax, double *fcrossover, char error_string[ ])
Output: no_motors, max_range (array of three numbers), fmin, fmax, fcrossover,error_string (80+ characters long), function-return->Error flag
The add_controller function adds or updates one controller in the tuner driver object
short add_controller(short controller_number, char driver[ ], char model[ ], int timeout, int address, long delay_ms, char error_string[ ])
Output: error_string, function-return->Error flag
|
[
"I'm not sure about your exact problem, but here's a couple general tips:\nFor those functions that you are calling outside of the constructor, I would strongly recommend setting their argtypes in the constructor as well. Once you've declared the argtypes, you shouldn't need to cast all the arguments as c_short, c_double, etc. Moreover, if you do accidentally pass an incorrect argument to a C function, Python will raise a runtime error instead of crashing within the DLL.\nAnother minor detail, but you should be using x = 0; byref(x) or maybe POINTER(c_double)() instead of pointer(c_double()) in the tuner and controller.\nI've been writing some ctypes classes in Python 2.6 recently as well, and I haven't seen any issues like what you're describing. Since there apparently aren't any Python bug reports on that either, I strongly believe that there's just a minute detail that we are both overlooking in your method that is having a problem.\n",
"Are any of the parameters in add-controller or add-tuner actually return values?\nStrongly recommend that you define prototypes of your functions, rather than calling them direct with casts of all the parameters.\nI'm sure you've read this page already, but the section you want to look at is Function Prototypes. Makes the code much cleaner and easier to trace/debug.\nAlso -- as Mark Rushakoff mentions too -- using pointer(c_double()) and like in your call is pretty icky. I have much better luck w/ POINTER(), and recommend again that you predeclare the value as a variable, and pass the variable in your function call. Then at least you can examine its value afterward for strange behavior.\nEDIT: So your prototype and call will look something like this:\nprototype = WINFUNCTYPE(\n c_int, # Return value (correct? Guess)\n c_short, # tuner_number\n c_char_p, # file_path\n c_char_p, # name\n c_int, # 0?\n c_int, # 0?\n c_long, # 0?\n c_short, # serial_number\n c_char_p, # error_string\n)\n# 1 input, 2 output, 4 input default to zero (I think; check doc page)\nparamflags = (1, 'TunerNumber' ), (1, 'FilePath' ), (1, 'Name' ), ...\nAddController = prototype(('add_controller', WinDLL.MlibTuners), paramflags)\n\nThen your call is much cleaner:\narg1 = 0\narg2 = 0\narg3 = 0\nAddController(tuner_number, self.file_path, name, arg1, arg2, arg3, \n serial_number, self.error_string)\n\n",
"I found out that the only way to call the functions in the exported DLL was to use the DLL through a parameter in each method. (the program exports the dll and in each method called it will send it as a parameter).\nIt looks pretty ugly but that's the only way I found to be working for me. I even tried exporting the DLL as an class attribute. The system I'm working with is pretty hefty so I guess there is some boboo-code somewhere that makes it fail. Thanks for all the feedback and tips!\n/Mazdak\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"automation",
"ctypes",
"dll",
"oop",
"python"
] |
stackoverflow_0001170372_automation_ctypes_dll_oop_python.txt
|
Q:
Reading files in python
Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly:
import os.path
filename = "A 180 mb large file.data"
size = os.path.getsize(filename)
f = open(filename, "r")
contents = f.read()
f.close()
print "The real filesize is", size
print "The read filesize is", len(contents)
f = open(filename, "r")
size = 0
while True:
contents = f.read(4)
if not contents: break
size += len(contents)
f.close()
print "this time it's", size
Outputs:
The real filesize is 183574528
The read filesize is 10322
this time it's 13440
Somebody knows whats going on here? :)
A:
If your file confuses the C libraries, then your results are expected.
The OS thinks it's 180Mb.
However, there are null bytes scattered around, which can confuse the C stdio libraries.
Try opening the file with "rb" and see if you get different results.
A:
The first is the filesize in bytes, the other times you read the file as text and count characters. Change all open(filename, "r") to open(filename, "rb") and it works.
A:
This is not about strings : Python is perfectly happy with null bytes in strings.
This is because you are on Windows and you open the file in text mode, so it converts all "\n" into "\r\n", thus destroying all your binary data.
Open your file in binary mode with mode "rb"
|
Reading files in python
|
Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly:
import os.path
filename = "A 180 mb large file.data"
size = os.path.getsize(filename)
f = open(filename, "r")
contents = f.read()
f.close()
print "The real filesize is", size
print "The read filesize is", len(contents)
f = open(filename, "r")
size = 0
while True:
contents = f.read(4)
if not contents: break
size += len(contents)
f.close()
print "this time it's", size
Outputs:
The real filesize is 183574528
The read filesize is 10322
this time it's 13440
Somebody knows whats going on here? :)
|
[
"If your file confuses the C libraries, then your results are expected.\nThe OS thinks it's 180Mb.\nHowever, there are null bytes scattered around, which can confuse the C stdio libraries.\nTry opening the file with \"rb\" and see if you get different results.\n",
"The first is the filesize in bytes, the other times you read the file as text and count characters. Change all open(filename, \"r\") to open(filename, \"rb\") and it works.\n",
"This is not about strings : Python is perfectly happy with null bytes in strings.\nThis is because you are on Windows and you open the file in text mode, so it converts all \"\\n\" into \"\\r\\n\", thus destroying all your binary data.\nOpen your file in binary mode with mode \"rb\"\n"
] |
[
5,
3,
0
] |
[] |
[] |
[
"file",
"python"
] |
stackoverflow_0001224391_file_python.txt
|
Q:
Convolution of two functions in Python
I will have to implement a convolution of two functions in Python, but SciPy/Numpy appear to have functions only for the convolution of two arrays.
Before I try to implement this by using the the regular integration expression of convolution, I would like to ask if someone knows of an already available module that performs these operations.
Failing that, which of the several kinds of integration that SciPy provides is the best suited for this?
Thanks!
A:
You could try to implement the Discrete Convolution if you need it point by point.
A:
Yes, SciPy/Numpy is mostly concerned about arrays.
If you can tolerate an approximate solution, and your functions only operate over a range of value (not infinite) you can fill an array with the values and convolve the arrays.
If you want something more "correct" calculus-wise you would probably need a powerful solver (mathmatica, maple...)
|
Convolution of two functions in Python
|
I will have to implement a convolution of two functions in Python, but SciPy/Numpy appear to have functions only for the convolution of two arrays.
Before I try to implement this by using the the regular integration expression of convolution, I would like to ask if someone knows of an already available module that performs these operations.
Failing that, which of the several kinds of integration that SciPy provides is the best suited for this?
Thanks!
|
[
"You could try to implement the Discrete Convolution if you need it point by point.\n",
"Yes, SciPy/Numpy is mostly concerned about arrays.\nIf you can tolerate an approximate solution, and your functions only operate over a range of value (not infinite) you can fill an array with the values and convolve the arrays.\nIf you want something more \"correct\" calculus-wise you would probably need a powerful solver (mathmatica, maple...)\n"
] |
[
2,
1
] |
[] |
[] |
[
"convolution",
"python"
] |
stackoverflow_0001222147_convolution_python.txt
|
Q:
List Comprehensions in Python : efficient selection in a list
Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a distance to an other element).
I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code
result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
But myFunction is a very time-consuming function, and the originalList quite big. So doing like that, myFunction will be call twice for every selected element.
So, is there a way to avoid this ??
I have two other possibilities, but they are not so good:
the first one, is to create the
unfiltered list
unfiltered = [ (myFunction(C),C) for C in originalList ]
and then sort it
result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
but in that case, I duplicate my
originalList and waste some memory
(the list could be quite big - more
than 10,000 elements)
the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). myFunction stores it last
result in a global variable (lastResult for example), and this value is re-used in the
List comprehension
result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
Do you have any better idea to achieve that, in an efficient and pythonic way ??
Thanks for your answers.
A:
Sure, the difference between the following two:
[f(x) for x in list]
and this:
(f(x) for x in list)
is that the first will generate the list in memory, whereas the second is a new generator, with lazy evaluation.
So, simply write the "unfiltered" list as a generator instead. Here's your code, with the generator inline:
def myFunction(x):
print("called for: " + str(x))
return x * x
originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
limit = 10
result = [C2 for C2 in ((myFunction(C), C) for C in originalList) if C2[0] < limit]
# result = [C2 for C2 in [(myFunction(C), C) for C in originalList] if C2[0] < limit]
Note that you will not see a difference in the printout from the two, but if you were to look at memory usage, the second statement which is commented out, will use more memory.
To do a simple change to your code in your question, rewrite unfiltered as this:
unfiltered = [ (myFunction(C),C) for C in originalList ]
^ ^
+---------- change these to (..) ---------+
|
v
unfiltered = ( (myFunction(C),C) for C in originalList )
A:
Don't use a list comprehension; a normal for loop is fine here.
A:
Just compute the distances beforehand and then filter the results:
with_distances = ((myFunction(C), C) for C in originalList)
result = [C for C in with_distances if C[0] < limit]
Note: instead of building a new list, I use a generator expression to build the distance/element pairs.
A:
Some options:
Use memoization
Use a normal for loop
Create an unfiltered list, then filter it (your option 1). The 'wasted' memory will be reclaimed by the GC very quickly - it's not something you need to worry about.
A:
Lasse V. Karlsen has an excellent reply to your question.
If your distance computation is slow, I guess your elements are polylines, or something like that, right ?
There are lots of ways to make it faster :
If the distance between bounding boxes of objects is > X, then it follows that the distance between those objects is > X. So you only need to compute distance between bounding boxes.
If you want all objects that are at a distance less than X from object A, only objects whose bounding box intersect A's bounding box enlarged by X are potential matches.
Using the second point you can probably drop lots of candidate matches and only do the slow computation when needed.
Bounding boxes must be cached beforehand.
If you really have a lot of objects you could also use space partitioning...
Or convex enclosing polys if you are in 3D
A:
Rather than using a global variable as in your option 2, you could rely on the fact that in Python parameters are passed by object - that is, the object that is passed into your myFunction function is the same object as the one in the list (this isn't exactly the same thing as call by reference, but it's close enough).
So, if your myFunction set an attribute on the object - say, _result - you could filter by that attribute:
result = [(_result, C) for C in originalList if myFunction(C) < limit]
and your myFunction might look like this:
def myFunction(obj):
obj._result = ... calculation ....
return obj._result
A:
What's wrong with option 1?
"duplicate my originalList and waste some memory (the list could be quite big - more than 10,000 elements)"
10,000 elements is only 10,000 pointers to tuples that point to existing objects. Think 160K or so of memory. Hardly worth talking about.
|
List Comprehensions in Python : efficient selection in a list
|
Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a distance to an other element).
I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code
result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
But myFunction is a very time-consuming function, and the originalList quite big. So doing like that, myFunction will be call twice for every selected element.
So, is there a way to avoid this ??
I have two other possibilities, but they are not so good:
the first one, is to create the
unfiltered list
unfiltered = [ (myFunction(C),C) for C in originalList ]
and then sort it
result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
but in that case, I duplicate my
originalList and waste some memory
(the list could be quite big - more
than 10,000 elements)
the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). myFunction stores it last
result in a global variable (lastResult for example), and this value is re-used in the
List comprehension
result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
Do you have any better idea to achieve that, in an efficient and pythonic way ??
Thanks for your answers.
|
[
"Sure, the difference between the following two:\n[f(x) for x in list]\n\nand this:\n(f(x) for x in list)\n\nis that the first will generate the list in memory, whereas the second is a new generator, with lazy evaluation.\nSo, simply write the \"unfiltered\" list as a generator instead. Here's your code, with the generator inline:\ndef myFunction(x):\n print(\"called for: \" + str(x))\n return x * x\n\noriginalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nlimit = 10\nresult = [C2 for C2 in ((myFunction(C), C) for C in originalList) if C2[0] < limit]\n# result = [C2 for C2 in [(myFunction(C), C) for C in originalList] if C2[0] < limit]\n\nNote that you will not see a difference in the printout from the two, but if you were to look at memory usage, the second statement which is commented out, will use more memory.\nTo do a simple change to your code in your question, rewrite unfiltered as this:\nunfiltered = [ (myFunction(C),C) for C in originalList ]\n ^ ^\n +---------- change these to (..) ---------+\n |\n v\nunfiltered = ( (myFunction(C),C) for C in originalList )\n\n",
"Don't use a list comprehension; a normal for loop is fine here.\n",
"Just compute the distances beforehand and then filter the results:\nwith_distances = ((myFunction(C), C) for C in originalList)\nresult = [C for C in with_distances if C[0] < limit]\n\nNote: instead of building a new list, I use a generator expression to build the distance/element pairs.\n",
"Some options:\n\nUse memoization\nUse a normal for loop\nCreate an unfiltered list, then filter it (your option 1). The 'wasted' memory will be reclaimed by the GC very quickly - it's not something you need to worry about.\n\n",
"Lasse V. Karlsen has an excellent reply to your question.\nIf your distance computation is slow, I guess your elements are polylines, or something like that, right ?\nThere are lots of ways to make it faster :\n\nIf the distance between bounding boxes of objects is > X, then it follows that the distance between those objects is > X. So you only need to compute distance between bounding boxes.\nIf you want all objects that are at a distance less than X from object A, only objects whose bounding box intersect A's bounding box enlarged by X are potential matches.\n\nUsing the second point you can probably drop lots of candidate matches and only do the slow computation when needed.\nBounding boxes must be cached beforehand.\nIf you really have a lot of objects you could also use space partitioning...\nOr convex enclosing polys if you are in 3D\n",
"Rather than using a global variable as in your option 2, you could rely on the fact that in Python parameters are passed by object - that is, the object that is passed into your myFunction function is the same object as the one in the list (this isn't exactly the same thing as call by reference, but it's close enough).\nSo, if your myFunction set an attribute on the object - say, _result - you could filter by that attribute:\nresult = [(_result, C) for C in originalList if myFunction(C) < limit]\n\nand your myFunction might look like this:\ndef myFunction(obj):\n obj._result = ... calculation ....\n return obj._result\n\n",
"What's wrong with option 1?\n\"duplicate my originalList and waste some memory (the list could be quite big - more than 10,000 elements)\"\n10,000 elements is only 10,000 pointers to tuples that point to existing objects. Think 160K or so of memory. Hardly worth talking about.\n"
] |
[
9,
3,
3,
1,
1,
0,
0
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0001222677_list_comprehension_python.txt
|
Q:
How to setup mod_python configuration variables?
I'm running a Python server with mod_python, and I've run into some issues with configuration variables. This is actually two questions rolled into one, because I think they are highly related:
I need a way to configure variables that will be available in Python while running. I currently just have a module that sets some name-value pairs that I import into other modules, but I was reading up on PythonOption recently and was wondering what advantages would be gained from using that instead.
I need a way to store state on the server. I've got access to an API that's limited to running X number of times a day, and once it hits that limit, I need to revert to my (lesser) code. I'm wondering how I can keep track of how many times I've run the query in a day.
I thought about using a file or the database, but I'm afraid I will slow down requests by having everyone try to access the same file or row at once. Is there a better way to set this up in mod_python?
A:
Using PythonOption lets you configure stuff that may need to change from server to server. I wouldn't use it too much, though, because messing with the Apache configuration directives is kind of a pain (plus it requires reloading the server). You might consider something like using PythonOption to specify the name of a settings file that contains the actual configuration variables. (Or you could just look in a standard location for the settings file, like most frameworks do)
If you really don't want to consider a file or a database, try memcached. It's basically a very simple database (get, set, and clear by key only) that's stored entirely in RAM, so it's very fast. If all you need to store is a counter variable, though, you could probably just stick it in a Python module as a global variable, unless you're worried about the counter being reset when the module gets reloaded.
A:
I need a way to configure variables that will be available in Python while running.
Do what Django does. Use a simple importable script of Python assignment statements.
I need a way to store state on the server.
Do what Django does. Use SQLite3.
Also, read PEP 333 and structure your application components to support WSGI. This should be a relatively small revision to have the proper WSGI structure to existing code.
When you switch from mod_python to mod_wsgi, you can find numerous components to do these things for you and reduce the amount of code you've written.
|
How to setup mod_python configuration variables?
|
I'm running a Python server with mod_python, and I've run into some issues with configuration variables. This is actually two questions rolled into one, because I think they are highly related:
I need a way to configure variables that will be available in Python while running. I currently just have a module that sets some name-value pairs that I import into other modules, but I was reading up on PythonOption recently and was wondering what advantages would be gained from using that instead.
I need a way to store state on the server. I've got access to an API that's limited to running X number of times a day, and once it hits that limit, I need to revert to my (lesser) code. I'm wondering how I can keep track of how many times I've run the query in a day.
I thought about using a file or the database, but I'm afraid I will slow down requests by having everyone try to access the same file or row at once. Is there a better way to set this up in mod_python?
|
[
"\nUsing PythonOption lets you configure stuff that may need to change from server to server. I wouldn't use it too much, though, because messing with the Apache configuration directives is kind of a pain (plus it requires reloading the server). You might consider something like using PythonOption to specify the name of a settings file that contains the actual configuration variables. (Or you could just look in a standard location for the settings file, like most frameworks do)\nIf you really don't want to consider a file or a database, try memcached. It's basically a very simple database (get, set, and clear by key only) that's stored entirely in RAM, so it's very fast. If all you need to store is a counter variable, though, you could probably just stick it in a Python module as a global variable, unless you're worried about the counter being reset when the module gets reloaded.\n\n",
"\nI need a way to configure variables that will be available in Python while running. \nDo what Django does. Use a simple importable script of Python assignment statements.\nI need a way to store state on the server. \nDo what Django does. Use SQLite3.\n\nAlso, read PEP 333 and structure your application components to support WSGI. This should be a relatively small revision to have the proper WSGI structure to existing code.\nWhen you switch from mod_python to mod_wsgi, you can find numerous components to do these things for you and reduce the amount of code you've written.\n"
] |
[
1,
0
] |
[] |
[] |
[
"configuration",
"mod_python",
"python"
] |
stackoverflow_0001224978_configuration_mod_python_python.txt
|
Q:
Convincing others of Ruby over Python and PHP
G'day folks. I'm trying to introduce Ruby at work, and a few people are interested. However, I've been asked to present the benefits of Ruby over Python and PHP.
I've broken this down into 2 parts:
1) show Python and Ruby's advantages over PHP;
2) show Ruby's advantages over Python.
The first is easy. I'll explain things like:
Everything's an object.
Python and Ruby are easier to read and write.
For the second, I'm thinking of:
Ruby has many conveniences, which makes it easier to read and write. Eg: Optional brackets, and being able to open built-ins, allows for things like 2.days.from_now
RSpec is miles ahead of Python's TDD and BDD frameworks.
GitHub and RubyForge are fantastic resources for finding, releasing, and collaborating on software.
Do you have any suggestions? I'm all ears!
A:
If your goal is to show why language X is better than language Y, you're stuck in subjective-land where there are no right answers.
No, Ruby is not better than PHP or Python. It might be more suited for a given purpose, and for that you can give specific examples. PHP is a poor choice for writing an SMTP server; Ruby and Python will serve you better (in fact, in Python it can be done in just a few lines, can't speak for Ruby though). On the other hand, PHP is better suited than Ruby for writing a one-off, short backend for an email submission form. The code is short, easy to maintain, quick to write, etc.
PHP has an absolutely huge developer base, making programmers easy to find, which comes in handy if you ever want to out-source any aspect of the development chain. On the other hand, it's also terrifically easy to write horrible code in PHP, and there is more than enough of that going around.
Python has a much larger user base than Ruby, and indeed is the primary language that RedHat uses for developing system tools. So if you're on a RedHat derived server (and statistically, chances are pretty good that you are if you're using Linux) then Python is guaranteed to be already in-place and working properly, etc.
In short, weigh the benefits, make a decision, but don't assume that people will agree with you; after all it's just an opinion.
Edit
It just occurred to me that I failed to state the whole point: you shouldn't be trying to convince other people that they should use Ruby over Python/PHP. Instead you should be trying to determine whether you should use Ruby over Python/PHP.
You can't go fact-finding like this having already determined what the answer will be -- that's not helpful. Instead you should be gathering information on the benefits and drawbacks of each language and weighing that against the requirements of your company. Once you come to a conclusion, you'll already have a preponderance of evidence showing it was the correct one.
A:
Don't get sucked into comparative arguments - unless you're experienced in all three languages, you'll just be revealing your ignorance - especially when claiming "X can't do Y". The true fans will take you down.
Instead, show off what ruby can do. It's a great language, but that has nothing to do with how well people talk about it. What matters is the code. So show off. Demonstrate your productivity, reliability, and flexibility with the language. Make it the easiest thing to follow at the code review. Have suites and suites of tests. Read up on sneaky techniques from RedHanded if you have to. Win your coworkers with your code -- it'll be far more convincing than your words ever could be.
A:
Hmm, as an active programmer in all three languages I simply can't agree with the sentiment that either is better than the other. Sure, Python and Ruby are more object-oriented, but that's not a requirement to be better, it's only a convenience. You can't beat the community of PHP and the legacy (for good and for bad) of code, nor ignore the direction PHP is taking for the future, the mass of support, the distributed servers ready for it, and so on.
If you want to focus on syntax, then all three have their strong and weak points. If you want to talk about back-end technology, then as all three are moving active open-source projects, there really is no winner.
Except, you, the programmer, who can mix and choose what best suits you. Remember that even if you think Ruby is the best thing since NAND gates it doesn't mean others follow. And remember also that we're all different; some people actually like Java and .Net, just like others love LISP. We're all different, and I doubt any of the Ruby/Python/PHP contenders are any better than the other. Sorry.
A:
Devil's advocate maybe...
Everything's an object.
This is a feature of Ruby, but it is not self-explanatory as to why this is a benefit. You would need to pre-prepare an argument for why that is a benefit. When convincing somebody of something's superiority, always think in terms of showing the benefits, not the features.
Python and Ruby are easier to read and write.
This is a very big claim to make, and I would not be comfortable making such a claim without a substantial amount of credible objective third party evidence supporting this. If not, and I suspect such a claim really couldn't be backed up, I would play it safe and avoid making such a claim. Making a claim this substantial, but only backing it up with personal opinion or anecdotal evidence would not be a good idea.
Ruby has many conveniences, which
makes it easier to read and write. Eg:
Optional brackets, and being able to
open built-ins, allows for things like
2.days.from_now
Again, you will need to think benefits, not features. It may be true that it has optional brackets, but you cannot just mention a feature, you have to explain its benefit - why that feature is a better idea than any other approach. Personally I am not sure that 'optional' syntax is ever a good idea, and would need a fair bit of evidence to convince me that it was.
GitHub and RubyForge are fantastic resources for finding,
releasing, and collaborating on
software.
That's good. There are also similar resources for languages other than Ruby - again, you will need to not only mention the existence of these but explain how they are better than the alternatives.
Good luck.
A:
If you really want to show Ruby is better (assuming it is for your application!), why not try writing a small app from scratch in front of them? It doesn't have to be big, but something relavent to what you'll eventually be using it for is a good idea.
Write the app in all three languages including any configuration for the server (I'm assuming you're writing a web app here using DJango / Rails / PHP right?) and show how much faster you are, how much cleaner the code is etc. ...assuming it is ;-)
You can finish up by asking them what they'd like to add to it and then try adding that feature if it's a small change. Nothing like a bit of audience participation - people like applauding themselves. If you get them involved they're more likely to accept the winner.
For the record, I've tried all three and would agree that both Ruby and Python seem to result in cleaner code. I'd go for Python over Ruby though - there was something clunky about the syntax of Ruby when I tried it that I just didn't experience with Python.
A:
You're going to have a tough sell over python. GitHub is written in Ruby, not for ruby per se, by the way.
For python one has BitBucket (even though I do prefer git), as well as pypi.
Correct me if I'm wrong, but it sounds like you haven't looked at python code all that much. (I've written buckets of both python and Ruby by the way) I find it much more readable, especially when you're working on code that's not your own.
Anyways, not really answering your question, and don't really want to contribute more to the flame war.
A:
Actually no one ever conviced me (at least directly), to use one programming language or another.
I used to have a certain need for clearness (if you might call it that way) and some other criteria, a language and its ecosystem should meet. And you definitively will end up using some stdlib, and third-party resources, so you might want to look into them as well (and use them as arguments).
I am a fan of both, ruby and python (and these languages conviced me both by their design, their constant progress and their communities). The general notion of a scripting language makes them equally appealing. I found gem to be one of the slowest software I ever used. And personally, I think pythons stdlib is better organized than rubys. But I like Ruby Mixins, they are elegant and safe a lot of time.
In short: You could point your colleagues interest to some current hot spots, where coding is just hard, then show some alternatives in ruby. Rake is a great tool as well, demonstrate it ... Just be rationally passionate about it .. The rest will come ..
A:
All 3 languages have their place. As with any programming task you must pick the language best suited for the task. Python has list comprehensions, php is much better when embedding and generating html. Ruby is a great language too. One of the things I have found myself using in ruby a few times is the 'a'...'zzzzz' to generate all possible strings of size 1 - 5. They all have their advantages and are all better than the others at particular tasks.
A:
If you are inclined towards a language or a software then you will tend to see only the goodies compared to others. If you want to do real comparison then comapre pros and cons and see if Ruby is clear winner in terms of what you want to achieve with that language in your company. If you do this and your company see benefits of Ruby then surely they will use.
A:
Happy programmers == productive programmers
Ruby == Happy Programmers
So that must mean
Ruby == productive programmer
Convince them both these statements are true and you are there. Assuming of course Ruby makes you a happy programmer.
A:
This kind of post gives Ruby programmers a bad name. Ruby is Beethoven, Python is Bach. If you prefer one style to the other, fine, but don't try to argue the superiority of one over the other.
|
Convincing others of Ruby over Python and PHP
|
G'day folks. I'm trying to introduce Ruby at work, and a few people are interested. However, I've been asked to present the benefits of Ruby over Python and PHP.
I've broken this down into 2 parts:
1) show Python and Ruby's advantages over PHP;
2) show Ruby's advantages over Python.
The first is easy. I'll explain things like:
Everything's an object.
Python and Ruby are easier to read and write.
For the second, I'm thinking of:
Ruby has many conveniences, which makes it easier to read and write. Eg: Optional brackets, and being able to open built-ins, allows for things like 2.days.from_now
RSpec is miles ahead of Python's TDD and BDD frameworks.
GitHub and RubyForge are fantastic resources for finding, releasing, and collaborating on software.
Do you have any suggestions? I'm all ears!
|
[
"If your goal is to show why language X is better than language Y, you're stuck in subjective-land where there are no right answers.\nNo, Ruby is not better than PHP or Python. It might be more suited for a given purpose, and for that you can give specific examples. PHP is a poor choice for writing an SMTP server; Ruby and Python will serve you better (in fact, in Python it can be done in just a few lines, can't speak for Ruby though). On the other hand, PHP is better suited than Ruby for writing a one-off, short backend for an email submission form. The code is short, easy to maintain, quick to write, etc.\nPHP has an absolutely huge developer base, making programmers easy to find, which comes in handy if you ever want to out-source any aspect of the development chain. On the other hand, it's also terrifically easy to write horrible code in PHP, and there is more than enough of that going around.\nPython has a much larger user base than Ruby, and indeed is the primary language that RedHat uses for developing system tools. So if you're on a RedHat derived server (and statistically, chances are pretty good that you are if you're using Linux) then Python is guaranteed to be already in-place and working properly, etc.\nIn short, weigh the benefits, make a decision, but don't assume that people will agree with you; after all it's just an opinion.\n\nEdit\nIt just occurred to me that I failed to state the whole point: you shouldn't be trying to convince other people that they should use Ruby over Python/PHP. Instead you should be trying to determine whether you should use Ruby over Python/PHP. \nYou can't go fact-finding like this having already determined what the answer will be -- that's not helpful. Instead you should be gathering information on the benefits and drawbacks of each language and weighing that against the requirements of your company. Once you come to a conclusion, you'll already have a preponderance of evidence showing it was the correct one.\n",
"Don't get sucked into comparative arguments - unless you're experienced in all three languages, you'll just be revealing your ignorance - especially when claiming \"X can't do Y\". The true fans will take you down.\nInstead, show off what ruby can do. It's a great language, but that has nothing to do with how well people talk about it. What matters is the code. So show off. Demonstrate your productivity, reliability, and flexibility with the language. Make it the easiest thing to follow at the code review. Have suites and suites of tests. Read up on sneaky techniques from RedHanded if you have to. Win your coworkers with your code -- it'll be far more convincing than your words ever could be.\n",
"Hmm, as an active programmer in all three languages I simply can't agree with the sentiment that either is better than the other. Sure, Python and Ruby are more object-oriented, but that's not a requirement to be better, it's only a convenience. You can't beat the community of PHP and the legacy (for good and for bad) of code, nor ignore the direction PHP is taking for the future, the mass of support, the distributed servers ready for it, and so on.\nIf you want to focus on syntax, then all three have their strong and weak points. If you want to talk about back-end technology, then as all three are moving active open-source projects, there really is no winner.\nExcept, you, the programmer, who can mix and choose what best suits you. Remember that even if you think Ruby is the best thing since NAND gates it doesn't mean others follow. And remember also that we're all different; some people actually like Java and .Net, just like others love LISP. We're all different, and I doubt any of the Ruby/Python/PHP contenders are any better than the other. Sorry.\n",
"Devil's advocate maybe...\n\n\nEverything's an object.\n\n\nThis is a feature of Ruby, but it is not self-explanatory as to why this is a benefit. You would need to pre-prepare an argument for why that is a benefit. When convincing somebody of something's superiority, always think in terms of showing the benefits, not the features.\n\n\nPython and Ruby are easier to read and write.\n\n\nThis is a very big claim to make, and I would not be comfortable making such a claim without a substantial amount of credible objective third party evidence supporting this. If not, and I suspect such a claim really couldn't be backed up, I would play it safe and avoid making such a claim. Making a claim this substantial, but only backing it up with personal opinion or anecdotal evidence would not be a good idea.\n\n\nRuby has many conveniences, which\n makes it easier to read and write. Eg:\n Optional brackets, and being able to\n open built-ins, allows for things like\n 2.days.from_now\n\n\nAgain, you will need to think benefits, not features. It may be true that it has optional brackets, but you cannot just mention a feature, you have to explain its benefit - why that feature is a better idea than any other approach. Personally I am not sure that 'optional' syntax is ever a good idea, and would need a fair bit of evidence to convince me that it was.\n\n\nGitHub and RubyForge are fantastic resources for finding,\n releasing, and collaborating on\n software.\n\n\nThat's good. There are also similar resources for languages other than Ruby - again, you will need to not only mention the existence of these but explain how they are better than the alternatives.\nGood luck.\n",
"If you really want to show Ruby is better (assuming it is for your application!), why not try writing a small app from scratch in front of them? It doesn't have to be big, but something relavent to what you'll eventually be using it for is a good idea.\nWrite the app in all three languages including any configuration for the server (I'm assuming you're writing a web app here using DJango / Rails / PHP right?) and show how much faster you are, how much cleaner the code is etc. ...assuming it is ;-)\nYou can finish up by asking them what they'd like to add to it and then try adding that feature if it's a small change. Nothing like a bit of audience participation - people like applauding themselves. If you get them involved they're more likely to accept the winner.\nFor the record, I've tried all three and would agree that both Ruby and Python seem to result in cleaner code. I'd go for Python over Ruby though - there was something clunky about the syntax of Ruby when I tried it that I just didn't experience with Python.\n",
"You're going to have a tough sell over python. GitHub is written in Ruby, not for ruby per se, by the way.\nFor python one has BitBucket (even though I do prefer git), as well as pypi.\nCorrect me if I'm wrong, but it sounds like you haven't looked at python code all that much. (I've written buckets of both python and Ruby by the way) I find it much more readable, especially when you're working on code that's not your own.\nAnyways, not really answering your question, and don't really want to contribute more to the flame war.\n",
"Actually no one ever conviced me (at least directly), to use one programming language or another. \nI used to have a certain need for clearness (if you might call it that way) and some other criteria, a language and its ecosystem should meet. And you definitively will end up using some stdlib, and third-party resources, so you might want to look into them as well (and use them as arguments).\nI am a fan of both, ruby and python (and these languages conviced me both by their design, their constant progress and their communities). The general notion of a scripting language makes them equally appealing. I found gem to be one of the slowest software I ever used. And personally, I think pythons stdlib is better organized than rubys. But I like Ruby Mixins, they are elegant and safe a lot of time.\nIn short: You could point your colleagues interest to some current hot spots, where coding is just hard, then show some alternatives in ruby. Rake is a great tool as well, demonstrate it ... Just be rationally passionate about it .. The rest will come ..\n",
"All 3 languages have their place. As with any programming task you must pick the language best suited for the task. Python has list comprehensions, php is much better when embedding and generating html. Ruby is a great language too. One of the things I have found myself using in ruby a few times is the 'a'...'zzzzz' to generate all possible strings of size 1 - 5. They all have their advantages and are all better than the others at particular tasks.\n",
"If you are inclined towards a language or a software then you will tend to see only the goodies compared to others. If you want to do real comparison then comapre pros and cons and see if Ruby is clear winner in terms of what you want to achieve with that language in your company. If you do this and your company see benefits of Ruby then surely they will use.\n",
"Happy programmers == productive programmers\nRuby == Happy Programmers\n\nSo that must mean\nRuby == productive programmer\n\nConvince them both these statements are true and you are there. Assuming of course Ruby makes you a happy programmer.\n",
"This kind of post gives Ruby programmers a bad name. Ruby is Beethoven, Python is Bach. If you prefer one style to the other, fine, but don't try to argue the superiority of one over the other.\n"
] |
[
29,
16,
12,
5,
5,
2,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"python",
"ruby"
] |
stackoverflow_0000784584_python_ruby.txt
|
Q:
can someone help me understand this short .py
I'm trying to understand basic threading in python, I'm having trouble understanding how pooling works with the queue module. Heres the example server used in the howto I'm reading from: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/. Basically what I don't understand is how the variable pickledList ends up available to the threads scope to be shipped out to the client since its never passed to the thread anywhere in the code
import pickle
import Queue
import socket
import threading
# We'll pickle a list of numbers, yet again:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
# A revised version of our thread class:
class ClientThread ( threading.Thread ):
# Note that we do not override Thread's __init__ method.
# The Queue module makes this not necessary.
def run ( self ):
# Have our thread serve "forever":
while True:
# Get a client out of the queue
client = clientPool.get()
# Check if we actually have an actual client in the client variable:
if client != None:
print 'Received connection:', client [ 1 ] [ 0 ]
client [ 0 ].send ( pickledList )
for x in xrange ( 10 ):
print client [ 0 ].recv ( 1024 )
client [ 0 ].close()
print 'Closed connection:', client [ 1 ] [ 0 ]
# Create our Queue:
clientPool = Queue.Queue ( 0 )
# Start two threads:
for x in xrange ( 2 ):
ClientThread().start()
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
clientPool.put ( server.accept() )
A:
The pickledList variable is available as a global variable in the ClientThread class. See Short Description of Python Scoping Rules.
|
can someone help me understand this short .py
|
I'm trying to understand basic threading in python, I'm having trouble understanding how pooling works with the queue module. Heres the example server used in the howto I'm reading from: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/. Basically what I don't understand is how the variable pickledList ends up available to the threads scope to be shipped out to the client since its never passed to the thread anywhere in the code
import pickle
import Queue
import socket
import threading
# We'll pickle a list of numbers, yet again:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
# A revised version of our thread class:
class ClientThread ( threading.Thread ):
# Note that we do not override Thread's __init__ method.
# The Queue module makes this not necessary.
def run ( self ):
# Have our thread serve "forever":
while True:
# Get a client out of the queue
client = clientPool.get()
# Check if we actually have an actual client in the client variable:
if client != None:
print 'Received connection:', client [ 1 ] [ 0 ]
client [ 0 ].send ( pickledList )
for x in xrange ( 10 ):
print client [ 0 ].recv ( 1024 )
client [ 0 ].close()
print 'Closed connection:', client [ 1 ] [ 0 ]
# Create our Queue:
clientPool = Queue.Queue ( 0 )
# Start two threads:
for x in xrange ( 2 ):
ClientThread().start()
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
clientPool.put ( server.accept() )
|
[
"The pickledList variable is available as a global variable in the ClientThread class. See Short Description of Python Scoping Rules.\n"
] |
[
4
] |
[
"Threads don't have their own namespace. pickledList is defined as a global, so it is accessible to the object. Technically it should have had a global pickledList at the top of the function to make that clear, but it's not always needed.\nEDIT\nBy make it clear, I mean \"make it clear to a human.\" \n"
] |
[
-2
] |
[
"multithreading",
"python"
] |
stackoverflow_0001227448_multithreading_python.txt
|
Q:
What is a good configuration file library for c thats not xml (preferably has python bindings)?
I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What would you recommend, or what method of reading/writing configuration settings do you prefer?
A:
YaML :)
A:
If you're not married to Python, try Lua. It was originally designed for configuration.
A:
You could use a pure python solution like ConfigObj and then simply use the CPython API to query for settings. This assumes that your application embeds Python. If it doesn't, and if you are shipping Python anyway, it might make sense to just embed it. Your C .exe won't get that much bigger if it's a dynamic link, and you will have all the flexibility of Python at your disposal.
A:
Despite being hated by techies and disowned by Microsoft, INI files are actually quite popular with users, as they are easy to understand and edit. They are also very simple to write parsers for, should your libraries not already support them.
|
What is a good configuration file library for c thats not xml (preferably has python bindings)?
|
I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What would you recommend, or what method of reading/writing configuration settings do you prefer?
|
[
"YaML :)\n",
"If you're not married to Python, try Lua. It was originally designed for configuration.\n",
"You could use a pure python solution like ConfigObj and then simply use the CPython API to query for settings. This assumes that your application embeds Python. If it doesn't, and if you are shipping Python anyway, it might make sense to just embed it. Your C .exe won't get that much bigger if it's a dynamic link, and you will have all the flexibility of Python at your disposal.\n",
"Despite being hated by techies and disowned by Microsoft, INI files are actually quite popular with users, as they are easy to understand and edit. They are also very simple to write parsers for, should your libraries not already support them.\n"
] |
[
5,
1,
0,
0
] |
[] |
[] |
[
"c",
"configuration_management",
"python"
] |
stackoverflow_0001227031_c_configuration_management_python.txt
|
Q:
How can I order objects according to some attribute of the child in sqlalchemy?
Here is the situation: I have a parent model say BlogPost. It has many Comments. What I want is the list of BlogPosts ordered by the creation date of its' Comments. I.e. the blog post which has the most newest comment should be on top of the list. Is this possible with SQLAlchemy?
A:
http://www.sqlalchemy.org/docs/05/mappers.html#controlling-ordering
As of version 0.5, the ORM does not
generate ordering for any query unless
explicitly configured.
The “default” ordering for a
collection, which applies to
list-based collections, can be
configured using the order_by keyword
argument on relation():
A:
I had the same question as the parent when using the ORM, and GHZ's link contained the answer on how it's possible. In sqlalchemy, assuming BlogPost.comments is a mapped relation to the Comments table, you can't do:
session.query(BlogPost).order_by(BlogPost.comments.creationDate.desc())
, but you can do:
session.query(BlogPost).join(Comments).order_by(Comments.creationDate.desc())
|
How can I order objects according to some attribute of the child in sqlalchemy?
|
Here is the situation: I have a parent model say BlogPost. It has many Comments. What I want is the list of BlogPosts ordered by the creation date of its' Comments. I.e. the blog post which has the most newest comment should be on top of the list. Is this possible with SQLAlchemy?
|
[
"http://www.sqlalchemy.org/docs/05/mappers.html#controlling-ordering\n\nAs of version 0.5, the ORM does not\n generate ordering for any query unless\n explicitly configured.\nThe “default” ordering for a\n collection, which applies to\n list-based collections, can be\n configured using the order_by keyword\n argument on relation():\n\n",
"I had the same question as the parent when using the ORM, and GHZ's link contained the answer on how it's possible. In sqlalchemy, assuming BlogPost.comments is a mapped relation to the Comments table, you can't do:\n\nsession.query(BlogPost).order_by(BlogPost.comments.creationDate.desc())\n\n, but you can do:\n\nsession.query(BlogPost).join(Comments).order_by(Comments.creationDate.desc())\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0000492223_python_sqlalchemy.txt
|
Q:
Retrieving the return value of a Python script
I have an external C# program which executes a Python script using the Process class.
My script returns a numerical code and I want to retrieve it from my C# program. Is this possible?
The problem is, I'm getting the return code of python.exe instead of the code returned from my script. (For example, 3.)
A:
The interpreter does not return the value at the top of Python's stack, unless you do this:
if __name__ == "__main__":
sys.exit(main())
or if you make a call to sys.exit elsewhere.
Here's a lot more documentation on this issue.
|
Retrieving the return value of a Python script
|
I have an external C# program which executes a Python script using the Process class.
My script returns a numerical code and I want to retrieve it from my C# program. Is this possible?
The problem is, I'm getting the return code of python.exe instead of the code returned from my script. (For example, 3.)
|
[
"The interpreter does not return the value at the top of Python's stack, unless you do this:\nif __name__ == \"__main__\":\n sys.exit(main())\n\nor if you make a call to sys.exit elsewhere.\nHere's a lot more documentation on this issue.\n"
] |
[
8
] |
[] |
[] |
[
"c#",
"python"
] |
stackoverflow_0001228550_c#_python.txt
|
Q:
Cython and numpy speed
I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at that point. This method works very well and it's accurate enough.
The problem is that with pure python this takes more than one minute. With my cython code, it takes about 17 seconds. This still is too much. Do you have any hints how to speed-up this code:
import numpy as np
cimport numpy as np
cimport cython
FTYPE = np.float
ctypedef np.float_t FTYPE_t
@cython.boundscheck(False)
def delay(np.ndarray[FTYPE_t, ndim=1] f, np.ndarray[FTYPE_t, ndim=1] g):
cdef int size1 = f.shape[0]
cdef int size2 = g.shape[0]
cdef int max_correlation = 0
cdef int delay = 0
cdef int current_correlation, i, j
# Move second data set frame by frame
for i in range(0, size1 - size2):
current_correlation = 0
# Calculate correlation at that point
for j in range(size2):
current_correlation += f[<unsigned int>(i+j)] * g[j]
# Check if current correlation is highest so far
if current_correlation > max_correlation:
max_correlation = current_correlation
delay = i
return delay
A:
Edit:
There's now scipy.signal.fftconvolve which would be the preferred approach to doing the FFT based convolution approach that I describe below. I'll leave the original answer to explain the speed issue, but in practice use scipy.signal.fftconvolve.
Original answer:
Using FFTs and the convolution theorem will give you dramatic speed gains by converting the problem from O(n^2) to O(n log n). This is particularly useful for long data sets, like yours, and can give speed gains of 1000s or much more, depending on length. It's also easy to do: just FFT both signals, multiply, and inverse FFT the product. numpy.correlate doesn't use the FFT method in the cross-correlation routine and is better used with very small kernels.
Here's an example
from timeit import Timer
from numpy import *
times = arange(0, 100, .001)
xdata = 1.*sin(2*pi*1.*times) + .5*sin(2*pi*1.1*times + 1.)
ydata = .5*sin(2*pi*1.1*times)
def xcorr(x, y):
return correlate(x, y, mode='same')
def fftxcorr(x, y):
fx, fy = fft.fft(x), fft.fft(y[::-1])
fxfy = fx*fy
xy = fft.ifft(fxfy)
return xy
if __name__ == "__main__":
N = 10
t = Timer("xcorr(xdata, ydata)", "from __main__ import xcorr, xdata, ydata")
print 'xcorr', t.timeit(number=N)/N
t = Timer("fftxcorr(xdata, ydata)", "from __main__ import fftxcorr, xdata, ydata")
print 'fftxcorr', t.timeit(number=N)/N
Which gives the running times per cycle (in seconds, for a 10,000 long waveform)
xcorr 34.3761689901
fftxcorr 0.0768054962158
It's clear the fftxcorr method is much faster.
If you plot out the results, you'll see that they are very similar near zero time shift. Note, though, as you get further away the xcorr will decrease and the fftxcorr won't. This is because it's a bit ambiguous what to do with the parts of the waveform that don't overlap when the waveforms are shifted. xcorr treats it as zero and the FFT treats the waveforms as periodic, but if it's an issue it can be fixed by zero padding.
A:
The trick with this sort of thing is to find a way to divide and conquer.
Currently, you're sliding to every position and check every point at every position -- effectively an O( n ^ 2 ) operation.
You need to reduce the check of every point and the comparison of every position to something that does less work to determine a non-match.
For example, you could have a shorter "is this even close?" filter that checks the first few positions. If the correlation is above some threshold, then keep going otherwise give up and move on.
You could have a "check every 8th position" that you multiply by 8. If this is too low, skip it and move on. If this is high enough, then check all of the values to see if you've found the maxima.
The issue is the time required to do all these multiplies -- (f[<unsigned int>(i+j)] * g[j]) In effect, you're filling a big matrix with all these products and picking the row with the maximum sum. You don't want to compute "all" the products. Just enough of the products to be sure you've found the maximum sum.
The issue with finding maxima is that you have to sum everything to see if it's biggest. If you can turn this into a minimization problem, it's easier to abandon computing products and sums once an intermediate result exceeds a threshold.
(I think this might work. I have't tried it.)
If you used max(g)-g[j] to work with negative numbers, you'd be looking for the smallest, not the biggest. You could compute the correlation for the first position. Anything that summed to a bigger value could be stopped immediately -- no more multiplies or adds for that offset, shift to another.
A:
you can extract range(size2) from the external loop
you can use sum() instead of a loop to compute current_correlation
you can store correlations and delays in a list and then use max() to get the biggest one
|
Cython and numpy speed
|
I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at that point. This method works very well and it's accurate enough.
The problem is that with pure python this takes more than one minute. With my cython code, it takes about 17 seconds. This still is too much. Do you have any hints how to speed-up this code:
import numpy as np
cimport numpy as np
cimport cython
FTYPE = np.float
ctypedef np.float_t FTYPE_t
@cython.boundscheck(False)
def delay(np.ndarray[FTYPE_t, ndim=1] f, np.ndarray[FTYPE_t, ndim=1] g):
cdef int size1 = f.shape[0]
cdef int size2 = g.shape[0]
cdef int max_correlation = 0
cdef int delay = 0
cdef int current_correlation, i, j
# Move second data set frame by frame
for i in range(0, size1 - size2):
current_correlation = 0
# Calculate correlation at that point
for j in range(size2):
current_correlation += f[<unsigned int>(i+j)] * g[j]
# Check if current correlation is highest so far
if current_correlation > max_correlation:
max_correlation = current_correlation
delay = i
return delay
|
[
"Edit:\nThere's now scipy.signal.fftconvolve which would be the preferred approach to doing the FFT based convolution approach that I describe below. I'll leave the original answer to explain the speed issue, but in practice use scipy.signal.fftconvolve.\nOriginal answer:\nUsing FFTs and the convolution theorem will give you dramatic speed gains by converting the problem from O(n^2) to O(n log n). This is particularly useful for long data sets, like yours, and can give speed gains of 1000s or much more, depending on length. It's also easy to do: just FFT both signals, multiply, and inverse FFT the product. numpy.correlate doesn't use the FFT method in the cross-correlation routine and is better used with very small kernels.\nHere's an example\nfrom timeit import Timer\nfrom numpy import *\n\ntimes = arange(0, 100, .001)\n\nxdata = 1.*sin(2*pi*1.*times) + .5*sin(2*pi*1.1*times + 1.)\nydata = .5*sin(2*pi*1.1*times)\n\ndef xcorr(x, y):\n return correlate(x, y, mode='same')\n\ndef fftxcorr(x, y):\n fx, fy = fft.fft(x), fft.fft(y[::-1])\n fxfy = fx*fy\n xy = fft.ifft(fxfy)\n return xy\n\nif __name__ == \"__main__\":\n N = 10\n t = Timer(\"xcorr(xdata, ydata)\", \"from __main__ import xcorr, xdata, ydata\")\n print 'xcorr', t.timeit(number=N)/N\n t = Timer(\"fftxcorr(xdata, ydata)\", \"from __main__ import fftxcorr, xdata, ydata\")\n print 'fftxcorr', t.timeit(number=N)/N\n\nWhich gives the running times per cycle (in seconds, for a 10,000 long waveform)\nxcorr 34.3761689901\nfftxcorr 0.0768054962158\n\nIt's clear the fftxcorr method is much faster.\nIf you plot out the results, you'll see that they are very similar near zero time shift. Note, though, as you get further away the xcorr will decrease and the fftxcorr won't. This is because it's a bit ambiguous what to do with the parts of the waveform that don't overlap when the waveforms are shifted. xcorr treats it as zero and the FFT treats the waveforms as periodic, but if it's an issue it can be fixed by zero padding.\n",
"The trick with this sort of thing is to find a way to divide and conquer.\nCurrently, you're sliding to every position and check every point at every position -- effectively an O( n ^ 2 ) operation.\nYou need to reduce the check of every point and the comparison of every position to something that does less work to determine a non-match.\nFor example, you could have a shorter \"is this even close?\" filter that checks the first few positions. If the correlation is above some threshold, then keep going otherwise give up and move on.\nYou could have a \"check every 8th position\" that you multiply by 8. If this is too low, skip it and move on. If this is high enough, then check all of the values to see if you've found the maxima.\nThe issue is the time required to do all these multiplies -- (f[<unsigned int>(i+j)] * g[j]) In effect, you're filling a big matrix with all these products and picking the row with the maximum sum. You don't want to compute \"all\" the products. Just enough of the products to be sure you've found the maximum sum.\nThe issue with finding maxima is that you have to sum everything to see if it's biggest. If you can turn this into a minimization problem, it's easier to abandon computing products and sums once an intermediate result exceeds a threshold.\n(I think this might work. I have't tried it.)\nIf you used max(g)-g[j] to work with negative numbers, you'd be looking for the smallest, not the biggest. You could compute the correlation for the first position. Anything that summed to a bigger value could be stopped immediately -- no more multiplies or adds for that offset, shift to another.\n",
"\nyou can extract range(size2) from the external loop\nyou can use sum() instead of a loop to compute current_correlation\nyou can store correlations and delays in a list and then use max() to get the biggest one\n\n"
] |
[
37,
2,
2
] |
[] |
[] |
[
"cython",
"numpy",
"python"
] |
stackoverflow_0001199972_cython_numpy_python.txt
|
Q:
Problem with Twisted python - sending binary data
What I'm trying to do is fairly simple: send a file from client to server. First, the client sends information about the file - the size of it that is. Then it sends the actual file.
This is what I've done so far:
Server.py
from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver
import pickle
import sys
class Echo(LineReceiver):
def connectionMade(self):
self.factory.clients.append(self)
self.setRawMode()
def connectionLost(self, reason):
self.factory.clients.remove(self)
def lineReceived(self, data):
print "line", data
def rawDataReceived(self, data):
try:
obj = pickle.loads(data)
print obj
except:
print data
#self.transport.write("wa2")
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
factory.clients = []
reactor.listenTCP(8000,factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
Client.py
import pickle
from twisted.internet import reactor, protocol
import time
import os.path
from twisted.protocols.basic import LineReceiver
class EchoClient(LineReceiver):
def connectionMade(self):
file = "some file that is a couple of megs"
filesize = os.path.getsize(file)
self.sendLine(pickle.dumps({"size":filesize}))
f = open(file, "rb")
contents = f.read()
print contents[:20]
self.sendLine(contents[:20])
f.close()
# self.sendLine("hej")
# self.sendLine("wa")
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = EchoFactory()
reactor.connectTCP("localhost", 8000, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
The server will only output the deserialized object:
{'size': 183574528L}
How come? What happend to the 20 chars from the file I wanted to send?
If use the "hej" and "wa" sends instead, I will get them both (in the same message, not twice).
Somebody?
A:
You've set your server to raw mode with setRawMode(), so the callback rawDataReceived is being called with the incoming data (not lineReceived). If you print the data you receive in rawDataReceived, you see everything including the file content, but as you call pickle to deserialize the data, it's being ignored.
Either you change the way you send data to the server (I would suggest the netstring format) or you pass the content inside the pickle serialized object, and do this in one call.
self.sendLine(pickle.dumps({"size":filesize, 'content': contents[:20]}))
|
Problem with Twisted python - sending binary data
|
What I'm trying to do is fairly simple: send a file from client to server. First, the client sends information about the file - the size of it that is. Then it sends the actual file.
This is what I've done so far:
Server.py
from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver
import pickle
import sys
class Echo(LineReceiver):
def connectionMade(self):
self.factory.clients.append(self)
self.setRawMode()
def connectionLost(self, reason):
self.factory.clients.remove(self)
def lineReceived(self, data):
print "line", data
def rawDataReceived(self, data):
try:
obj = pickle.loads(data)
print obj
except:
print data
#self.transport.write("wa2")
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
factory.clients = []
reactor.listenTCP(8000,factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
Client.py
import pickle
from twisted.internet import reactor, protocol
import time
import os.path
from twisted.protocols.basic import LineReceiver
class EchoClient(LineReceiver):
def connectionMade(self):
file = "some file that is a couple of megs"
filesize = os.path.getsize(file)
self.sendLine(pickle.dumps({"size":filesize}))
f = open(file, "rb")
contents = f.read()
print contents[:20]
self.sendLine(contents[:20])
f.close()
# self.sendLine("hej")
# self.sendLine("wa")
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = EchoFactory()
reactor.connectTCP("localhost", 8000, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
The server will only output the deserialized object:
{'size': 183574528L}
How come? What happend to the 20 chars from the file I wanted to send?
If use the "hej" and "wa" sends instead, I will get them both (in the same message, not twice).
Somebody?
|
[
"You've set your server to raw mode with setRawMode(), so the callback rawDataReceived is being called with the incoming data (not lineReceived). If you print the data you receive in rawDataReceived, you see everything including the file content, but as you call pickle to deserialize the data, it's being ignored.\nEither you change the way you send data to the server (I would suggest the netstring format) or you pass the content inside the pickle serialized object, and do this in one call.\nself.sendLine(pickle.dumps({\"size\":filesize, 'content': contents[:20]}))\n\n"
] |
[
9
] |
[] |
[] |
[
"file",
"python",
"send",
"twisted"
] |
stackoverflow_0001228722_file_python_send_twisted.txt
|
Q:
Problem with hash function: hash(1) == hash(1.0)
I have an instance of dict with ints, floats, strings as keys, but the problem is when there are a as int and b as float, and float(a) == b, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in order to get corresponding values.
Example:
d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0}
d[1] == '1.0'
d[1.0] == '1.0'
d['1'] == 1
d['1.0'] == 1.0
What I need is:
d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0}
d[1] == '1'
d[1.0] == '1.0'
d['1'] == 1
d['1.0'] == 1.0
A:
Since 1 == 1.0, it would horribly break the semantics of hashing (and therefore dicts and sets) if it were the case that hash(1) != hash(1.0). More generally, it must ALWAYS be the case that x == y implies hash(x) == hash(y), for ALL x and y (there is of course no condition requiring the reverse implication to hold).
So your dict d has just three entries, as the second one you've written in the dict display overrides the first one. If you need to force equality to hold only between identical types (as opposed to numbers more generally), you need a wrapper such as:
class W(object):
def __init__(self, x):
self.x = x
self.t = type(x)
def __eq__(self, other):
t = type(other)
if t != type(self):
return False
return self.x == other.x and self.t == other.t
def __hash__(self):
return hash(self.x) ^ hash(self.t)
def __getattr__(self, name):
return getattr(self.x, name)
Depending on your exact needs you may also want to override other methods (other comparison methods such as __cmp__ or __le__, arithmetic ones, __repr__, etc etc). At any rate, this will allow you to build a dict similar to what you require, just use as keys W(1) instead of bare 1 and W(1.0) instead of bare 1.0 (you may not need to wrap non-numbers, although there's no harm if you choose to do so, and it may ease retrieval from your dict if all keys are equally wrapped).
A:
Using a float as a dictionary key is 'unwise' it's impossible to guarantee that two floats will evaluate to the same value.
The best thing is to multiply the keys to a predetermined number of decimal places and use that integer as the key.
edit: Sorry it seems you don't want a dict with real number keys, you simply want to format an output based on the type of input?
A:
If you really just need to know the difference, perhaps do something hackish like:
x = '1'
y = 1
hash(type(x) + x) != hash(type(y) + y)
A:
This doesn't solve your problem, but from Python 2.6's number documentation:
Implementors should be careful to make equal numbers equal and hash them to the same values.
Can you get by with making the float 1.00001, or something like that?
|
Problem with hash function: hash(1) == hash(1.0)
|
I have an instance of dict with ints, floats, strings as keys, but the problem is when there are a as int and b as float, and float(a) == b, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in order to get corresponding values.
Example:
d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0}
d[1] == '1.0'
d[1.0] == '1.0'
d['1'] == 1
d['1.0'] == 1.0
What I need is:
d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0}
d[1] == '1'
d[1.0] == '1.0'
d['1'] == 1
d['1.0'] == 1.0
|
[
"Since 1 == 1.0, it would horribly break the semantics of hashing (and therefore dicts and sets) if it were the case that hash(1) != hash(1.0). More generally, it must ALWAYS be the case that x == y implies hash(x) == hash(y), for ALL x and y (there is of course no condition requiring the reverse implication to hold).\nSo your dict d has just three entries, as the second one you've written in the dict display overrides the first one. If you need to force equality to hold only between identical types (as opposed to numbers more generally), you need a wrapper such as:\nclass W(object):\n\n def __init__(self, x):\n self.x = x\n self.t = type(x)\n\n def __eq__(self, other):\n t = type(other)\n if t != type(self):\n return False\n return self.x == other.x and self.t == other.t\n\n def __hash__(self):\n return hash(self.x) ^ hash(self.t)\n\n def __getattr__(self, name):\n return getattr(self.x, name)\n\nDepending on your exact needs you may also want to override other methods (other comparison methods such as __cmp__ or __le__, arithmetic ones, __repr__, etc etc). At any rate, this will allow you to build a dict similar to what you require, just use as keys W(1) instead of bare 1 and W(1.0) instead of bare 1.0 (you may not need to wrap non-numbers, although there's no harm if you choose to do so, and it may ease retrieval from your dict if all keys are equally wrapped).\n",
"Using a float as a dictionary key is 'unwise' it's impossible to guarantee that two floats will evaluate to the same value.\nThe best thing is to multiply the keys to a predetermined number of decimal places and use that integer as the key.\nedit: Sorry it seems you don't want a dict with real number keys, you simply want to format an output based on the type of input?\n",
"If you really just need to know the difference, perhaps do something hackish like:\nx = '1'\ny = 1\n\nhash(type(x) + x) != hash(type(y) + y)\n\n",
"This doesn't solve your problem, but from Python 2.6's number documentation:\n\nImplementors should be careful to make equal numbers equal and hash them to the same values. \n\nCan you get by with making the float 1.00001, or something like that?\n"
] |
[
7,
6,
2,
1
] |
[] |
[] |
[
"dictionary",
"hash",
"python"
] |
stackoverflow_0001228475_dictionary_hash_python.txt
|
Q:
Globally-scoped variable: can its value change before it is picked up by the thread?
In the following code, you see that pickledList is being used by the thread and is set in the global scope.
If the variable that the thread was using was set dynamically somewhere down below in that final while loop, is it possible that its value could change before the thread got to use it? How can I set a value dynamically in the loop, send it off to the thread and make sure that its value doesn't change before the thread gets to use it?
import pickle
import Queue
import socket
import threading
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
class ClientThread ( threading.Thread ):
def run ( self ):
while True:
client = clientPool.get()
if client != None:
print 'Received connection:', client [ 1 ] [ 0 ]
client [ 0 ].send ( pickledList )
for x in xrange ( 10 ):
print client [ 0 ].recv ( 1024 )
client [ 0 ].close()
print 'Closed connection:', client [ 1 ] [ 0 ]
clientPool = Queue.Queue ( 0 )
for x in xrange ( 2 ):
ClientThread().start()
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
while True:
clientPool.put ( server.accept() )
EDIT:
Here is a better example of my problem. If you run this, sometimes the values change before the thread can output them, causing some to be skipped:
from threading import Thread
class t ( Thread ):
def run(self):
print "(from thread) ",
print i
for i in range(1, 50):
print i
t().start()
How can I pass the value in i to the thread in such a way that its no longer bound to the variable, so that if the value stored in i changes, the value the thread is working with is not affected.
A:
Option 1: you can pass arguments into each Thread when it is instantiated:
ClientThread(arg1, arg2, kwarg1="three times!").start()
in which case your run method will be called:
run(arg1, arg2, kwarg1="three times!")
by the Thread instance when you call start(). If you need to pass mutable objects (dicts, lists, instances) to the function, you must be sure to re-assign the global variable, not edit it in place.
Option 2: you can set an instance variable on your ClientThread objects:
myThread.setMyAttribute('new value')
With option 2 you need to be wary of race conditions etc. depending on what the method does. Using Locks whenever you're writing or reading data from/to a thread is a good idea.
Option 3: grab the global when run is first called and store a copy locally
run(self):
localVar = globalVar # only for immutable types
localList = globalList[:] # copy of a list
localDict = globalDict.copy() # Warning! Shallow copy only!
Option 1 is the right way to go if the value a thread is given never needs to change during its lifetime, Option 2 if the value does need to change. Option 3 is a hack.
With regard to generally passing variables/values around, you must remember with Python that immutable objects (strings, numbers, tuples) are passed by value and mutable objects (dicts, lists, class instances) are passed by reference.
Consequently, altering a string, number or tuple will not affect any instances previously passed that variable, however altering a dict, list or instance will do. Re-assigning a variable to a different object will not affect anything previously given the old value.
Globals certainly shouldn't be used for values that may change (if at all). Basically your example is doing it the wrong way.
|
Globally-scoped variable: can its value change before it is picked up by the thread?
|
In the following code, you see that pickledList is being used by the thread and is set in the global scope.
If the variable that the thread was using was set dynamically somewhere down below in that final while loop, is it possible that its value could change before the thread got to use it? How can I set a value dynamically in the loop, send it off to the thread and make sure that its value doesn't change before the thread gets to use it?
import pickle
import Queue
import socket
import threading
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
class ClientThread ( threading.Thread ):
def run ( self ):
while True:
client = clientPool.get()
if client != None:
print 'Received connection:', client [ 1 ] [ 0 ]
client [ 0 ].send ( pickledList )
for x in xrange ( 10 ):
print client [ 0 ].recv ( 1024 )
client [ 0 ].close()
print 'Closed connection:', client [ 1 ] [ 0 ]
clientPool = Queue.Queue ( 0 )
for x in xrange ( 2 ):
ClientThread().start()
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
while True:
clientPool.put ( server.accept() )
EDIT:
Here is a better example of my problem. If you run this, sometimes the values change before the thread can output them, causing some to be skipped:
from threading import Thread
class t ( Thread ):
def run(self):
print "(from thread) ",
print i
for i in range(1, 50):
print i
t().start()
How can I pass the value in i to the thread in such a way that its no longer bound to the variable, so that if the value stored in i changes, the value the thread is working with is not affected.
|
[
"Option 1: you can pass arguments into each Thread when it is instantiated:\nClientThread(arg1, arg2, kwarg1=\"three times!\").start()\n\nin which case your run method will be called:\nrun(arg1, arg2, kwarg1=\"three times!\")\n\nby the Thread instance when you call start(). If you need to pass mutable objects (dicts, lists, instances) to the function, you must be sure to re-assign the global variable, not edit it in place.\nOption 2: you can set an instance variable on your ClientThread objects:\nmyThread.setMyAttribute('new value')\n\nWith option 2 you need to be wary of race conditions etc. depending on what the method does. Using Locks whenever you're writing or reading data from/to a thread is a good idea.\nOption 3: grab the global when run is first called and store a copy locally\nrun(self):\n localVar = globalVar # only for immutable types\n localList = globalList[:] # copy of a list\n localDict = globalDict.copy() # Warning! Shallow copy only!\n\nOption 1 is the right way to go if the value a thread is given never needs to change during its lifetime, Option 2 if the value does need to change. Option 3 is a hack.\nWith regard to generally passing variables/values around, you must remember with Python that immutable objects (strings, numbers, tuples) are passed by value and mutable objects (dicts, lists, class instances) are passed by reference.\nConsequently, altering a string, number or tuple will not affect any instances previously passed that variable, however altering a dict, list or instance will do. Re-assigning a variable to a different object will not affect anything previously given the old value.\nGlobals certainly shouldn't be used for values that may change (if at all). Basically your example is doing it the wrong way.\n"
] |
[
3
] |
[] |
[] |
[
"multithreading",
"python",
"scope"
] |
stackoverflow_0001228655_multithreading_python_scope.txt
|
Q:
Convert list of floats into buffer in Python?
I am playing around with PortAudio and Python.
data = getData()
stream.write( data )
I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function:
def getData():
data = []
for i in range( 0, 1024 ):
data.append( 0.25 * math.sin( math.radians( i ) ) )
return data
Unfortunately that doesn't work because stream.write wants a buffer object to be passed in:
TypeError: argument 2 must be string or read-only buffer, not list
So my question is: How can I convert my list of floats in to a buffer object?
A:
import struct
def getData():
data = []
for i in range( 0, 1024 ):
data.append( 0.25 * math.sin( math.radians( i ) ) )
return struct.pack('f'*len(data), *data)
A:
Actually, the easiest way is to use the struct module. It is designed to convert from python objects to C-like "native" objects.
A:
Consider perhaps instead:
d = [0.25 * math.sin(math.radians(i)) for i in range(0, 1024)]
Perhaps you have to use a package like pickle to serialize the data first.
import pickle
f1 = open("test.dat", "wb")
pickle.dump(d, f1)
f1.close()
Then load it back in:
f2 = open("test.dat", "rb")
d2 = pickle.Unpickler(f2).load()
f2.close()
d2 == d
Returns True
|
Convert list of floats into buffer in Python?
|
I am playing around with PortAudio and Python.
data = getData()
stream.write( data )
I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function:
def getData():
data = []
for i in range( 0, 1024 ):
data.append( 0.25 * math.sin( math.radians( i ) ) )
return data
Unfortunately that doesn't work because stream.write wants a buffer object to be passed in:
TypeError: argument 2 must be string or read-only buffer, not list
So my question is: How can I convert my list of floats in to a buffer object?
|
[
"import struct\n\ndef getData():\n data = []\n for i in range( 0, 1024 ):\n data.append( 0.25 * math.sin( math.radians( i ) ) )\n return struct.pack('f'*len(data), *data)\n\n",
"Actually, the easiest way is to use the struct module. It is designed to convert from python objects to C-like \"native\" objects.\n",
"Consider perhaps instead:\nd = [0.25 * math.sin(math.radians(i)) for i in range(0, 1024)]\n\nPerhaps you have to use a package like pickle to serialize the data first.\nimport pickle\nf1 = open(\"test.dat\", \"wb\")\npickle.dump(d, f1)\nf1.close()\n\nThen load it back in:\nf2 = open(\"test.dat\", \"rb\")\nd2 = pickle.Unpickler(f2).load()\nf2.close()\n\n\nd2 == d\n\nReturns True\n"
] |
[
9,
2,
0
] |
[] |
[] |
[
"buffer",
"floating_point",
"list",
"python"
] |
stackoverflow_0001229202_buffer_floating_point_list_python.txt
|
Q:
Opening a wx.Frame in Python via a new thread
I have a frame that exists as a start up screen for the user to make a selection before the main program starts. After the user makes a selection I need the screen to stay up as a sort of splash screen until the main program finishes loading in back.
I've done this by creating an application and starting a thread:
class App(wx.App):
'''
Creates the main frame and displays it
Returns true if successful
'''
def OnInit(self):
try:
'''
Initialization
'''
self.newFile = False
self.fileName = ""
self.splashThread = Splash.SplashThread(logging, self)
self.splashThread.start()
#...More to the class
which launches a frame:
class SplashThread(threading.Thread):
def __init__(self, logger, app):
threading.Thread.__init__(self)
self.logger = logger
self.app = app
def run(self):
frame = Frame(self.logger, self.app)
frame.Show()
The app value is needed as it contains the callback which allows the main program to continue when the user makes their selection. The problem is that the startup screen only flashes for a millisecond then goes away, not allowing the user to make a selection and blocking the rest of start up.
Any ideas? Thanks in advance!
A:
You don't need threads for this. The drawback is that the splash window will block while loading but that is an issue only if you want to update it's contents (animate it) or if you want to be able to drag it. An issue that can be solved by periodically calling wx.SafeYield for example.
import time
import wx
class Loader(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
self.btn1 = wx.Button(self, label="Option 1")
self.btn2 = wx.Button(self, label="Option 2")
sizer.Add(self.btn1, flag=wx.EXPAND)
sizer.Add(self.btn2, flag=wx.EXPAND)
self.btn1.Bind(wx.EVT_BUTTON, self.OnOption1)
self.btn2.Bind(
wx.EVT_BUTTON, lambda e: wx.MessageBox("There is no option 2")
)
def OnOption1(self, event):
self.btn1.Hide()
self.btn2.Hide()
self.Sizer.Add(
wx.StaticText(self, label="Loading Option 1..."),
1, wx.ALL | wx.EXPAND, 15
)
self.Layout()
self.Update()
AppFrame(self).Show()
class AppFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent)
time.sleep(3)
parent.Hide()
# the top window (Loader) is hidden so the app needs to be told to exit
# when this window is closed
self.Bind(wx.EVT_CLOSE, lambda e: wx.GetApp().ExitMainLoop())
app = wx.PySimpleApp()
app.TopWindow = Loader()
app.TopWindow.Show()
app.MainLoop()
|
Opening a wx.Frame in Python via a new thread
|
I have a frame that exists as a start up screen for the user to make a selection before the main program starts. After the user makes a selection I need the screen to stay up as a sort of splash screen until the main program finishes loading in back.
I've done this by creating an application and starting a thread:
class App(wx.App):
'''
Creates the main frame and displays it
Returns true if successful
'''
def OnInit(self):
try:
'''
Initialization
'''
self.newFile = False
self.fileName = ""
self.splashThread = Splash.SplashThread(logging, self)
self.splashThread.start()
#...More to the class
which launches a frame:
class SplashThread(threading.Thread):
def __init__(self, logger, app):
threading.Thread.__init__(self)
self.logger = logger
self.app = app
def run(self):
frame = Frame(self.logger, self.app)
frame.Show()
The app value is needed as it contains the callback which allows the main program to continue when the user makes their selection. The problem is that the startup screen only flashes for a millisecond then goes away, not allowing the user to make a selection and blocking the rest of start up.
Any ideas? Thanks in advance!
|
[
"You don't need threads for this. The drawback is that the splash window will block while loading but that is an issue only if you want to update it's contents (animate it) or if you want to be able to drag it. An issue that can be solved by periodically calling wx.SafeYield for example.\nimport time\nimport wx\n\n\nclass Loader(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(sizer)\n self.btn1 = wx.Button(self, label=\"Option 1\")\n self.btn2 = wx.Button(self, label=\"Option 2\")\n sizer.Add(self.btn1, flag=wx.EXPAND)\n sizer.Add(self.btn2, flag=wx.EXPAND)\n self.btn1.Bind(wx.EVT_BUTTON, self.OnOption1)\n self.btn2.Bind(\n wx.EVT_BUTTON, lambda e: wx.MessageBox(\"There is no option 2\")\n )\n\n def OnOption1(self, event):\n self.btn1.Hide()\n self.btn2.Hide()\n self.Sizer.Add(\n wx.StaticText(self, label=\"Loading Option 1...\"),\n 1, wx.ALL | wx.EXPAND, 15\n )\n self.Layout()\n self.Update()\n AppFrame(self).Show()\n\nclass AppFrame(wx.Frame):\n def __init__(self, parent):\n wx.Frame.__init__(self, parent)\n time.sleep(3)\n parent.Hide()\n\n # the top window (Loader) is hidden so the app needs to be told to exit\n # when this window is closed\n self.Bind(wx.EVT_CLOSE, lambda e: wx.GetApp().ExitMainLoop())\n\n\napp = wx.PySimpleApp()\napp.TopWindow = Loader()\napp.TopWindow.Show()\napp.MainLoop()\n\n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"python",
"wxpython"
] |
stackoverflow_0001229525_multithreading_python_wxpython.txt
|
Q:
How to read/copy ctype pointers into python class?
This is a kind of follow-up from my last question if this can help you.
I'm defining a few ctype structures
class EthercatDatagram(Structure):
_fields_ = [("header", EthercatDatagramHeader),
("packet_data_length", c_int),
("packet_data", POINTER(c_ubyte)),
("work_count", c_ushort)]
class EthercatPacket(Structure):
_fields_ = [("ether_header", ETH_HEADER),
("Ethercat_header", EthercatHeader),
("data", POINTER(EthercatDatagram))]
note that this is parsed correctly by python, the missing classes are defined elsewhere.
My problem is when I call the following code
packet = EthercatPacket()
ethercap.RecvPacket(byref(packet))
print packet.data.header
This is incorrect. As I understand the problem, data is some kind of pointer so it isn't (really) mapped to EthercatDatagram, hence, the parser doesn't know the underlying header field.
is there some way to read that field as well as any other field represented by POINTER()?
A:
The square-bracket notation is indeed correct. For reference, here's a snippet from some ctypes code I recently made:
class Message(Structure):
_fields_ = [ ("id", BYTE), ("data", POINTER(BYTE)), ("data_length", DWORD) ]
def __repr__(self):
d = ' '.join(["0x%02X" % self.data[i] for i in range(self.data_length)])
return "<Message: id = 0x%02X, " % (self.id) + "data_length = " + str(self.data_length) + (self.data_length > 0 and (", data: " + d) or "") + ">"
A:
Ok I got it working
correct code was
print packet.data.header[0]
thanks to the 7 person who dared to look at the question
the google string for the answer was : python ctype dereference pointer
3rd hit
|
How to read/copy ctype pointers into python class?
|
This is a kind of follow-up from my last question if this can help you.
I'm defining a few ctype structures
class EthercatDatagram(Structure):
_fields_ = [("header", EthercatDatagramHeader),
("packet_data_length", c_int),
("packet_data", POINTER(c_ubyte)),
("work_count", c_ushort)]
class EthercatPacket(Structure):
_fields_ = [("ether_header", ETH_HEADER),
("Ethercat_header", EthercatHeader),
("data", POINTER(EthercatDatagram))]
note that this is parsed correctly by python, the missing classes are defined elsewhere.
My problem is when I call the following code
packet = EthercatPacket()
ethercap.RecvPacket(byref(packet))
print packet.data.header
This is incorrect. As I understand the problem, data is some kind of pointer so it isn't (really) mapped to EthercatDatagram, hence, the parser doesn't know the underlying header field.
is there some way to read that field as well as any other field represented by POINTER()?
|
[
"The square-bracket notation is indeed correct. For reference, here's a snippet from some ctypes code I recently made:\nclass Message(Structure):\n _fields_ = [ (\"id\", BYTE), (\"data\", POINTER(BYTE)), (\"data_length\", DWORD) ]\n def __repr__(self):\n d = ' '.join([\"0x%02X\" % self.data[i] for i in range(self.data_length)])\n return \"<Message: id = 0x%02X, \" % (self.id) + \"data_length = \" + str(self.data_length) + (self.data_length > 0 and (\", data: \" + d) or \"\") + \">\"\n\n",
"Ok I got it working\ncorrect code was \nprint packet.data.header[0]\n\nthanks to the 7 person who dared to look at the question\nthe google string for the answer was : python ctype dereference pointer\n3rd hit\n"
] |
[
1,
0
] |
[] |
[] |
[
"ctypes",
"pointers",
"python",
"variables"
] |
stackoverflow_0001229318_ctypes_pointers_python_variables.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.