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:
installing _imagingft
Possible Duplicate:
Python: The _imagingft C module is not installed
It seem that some of my problems with working with fonts, are due to the luck of _imagingft module. how can I install it? what are the steps
A:
It's created by building PIL with the FreeType development files in place.
|
installing _imagingft
|
Possible Duplicate:
Python: The _imagingft C module is not installed
It seem that some of my problems with working with fonts, are due to the luck of _imagingft module. how can I install it? what are the steps
|
[
"It's created by building PIL with the FreeType development files in place.\n"
] |
[
0
] |
[] |
[] |
[
"fonts",
"python"
] |
stackoverflow_0002185538_fonts_python.txt
|
Q:
Suggested GA operators for a TSP problem?
I'm building a genetic algorithm to tackle the traveling salesman problem. Unfortunately, I hit peaks that can sustain for over a thousand generations before mutating out of them and getting better results. What crossover and mutation operators generally do well in this case?
A:
Ordered mutation and ordered cross-over (see this article). Standard mutation and cross-over operations will usually result in invalid solutions (i.e. duplicate and/or missing cities in a route).
There was a similar question recently.
I have a Java applet that implements the TSP using ordered cross-over and mutation, if you are interested in comparing the performance of your implementation.
A:
If your problem is that peaks remain for over one thousand generations, then the problem might not be with the crossover and mutation operators. You might not be introducing or keeping enough variation to your population: I would examine the proportions of crossovers, of mutations, and of survivors from one generation to the next, and possibly raise the proportion of mutations.
A:
Could you please clarify
"Unfortunately, I hit peaks that can
sustain for over a thousand
generations before mutating out of
them and getting better results" ?
You could check on the crossover operators, which make sure that you have no repeating nodes in the child chromosomes. Couple of those crossover operators are the Order Crossover (OX) and the Edge Crossover operators.
Mutation can be as simple as simply swapping two positions in a single chromosome.
BTW, since you have tagged "python", take a look at Pyevolve, it also has a TSP example.
|
Suggested GA operators for a TSP problem?
|
I'm building a genetic algorithm to tackle the traveling salesman problem. Unfortunately, I hit peaks that can sustain for over a thousand generations before mutating out of them and getting better results. What crossover and mutation operators generally do well in this case?
|
[
"Ordered mutation and ordered cross-over (see this article). Standard mutation and cross-over operations will usually result in invalid solutions (i.e. duplicate and/or missing cities in a route).\nThere was a similar question recently.\nI have a Java applet that implements the TSP using ordered cross-over and mutation, if you are interested in comparing the performance of your implementation.\n",
"If your problem is that peaks remain for over one thousand generations, then the problem might not be with the crossover and mutation operators. You might not be introducing or keeping enough variation to your population: I would examine the proportions of crossovers, of mutations, and of survivors from one generation to the next, and possibly raise the proportion of mutations.\n",
"Could you please clarify \n\n\"Unfortunately, I hit peaks that can\n sustain for over a thousand\n generations before mutating out of\n them and getting better results\" ?\n\nYou could check on the crossover operators, which make sure that you have no repeating nodes in the child chromosomes. Couple of those crossover operators are the Order Crossover (OX) and the Edge Crossover operators. \nMutation can be as simple as simply swapping two positions in a single chromosome.\nBTW, since you have tagged \"python\", take a look at Pyevolve, it also has a TSP example.\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"algorithm",
"evolutionary_algorithm",
"genetic_algorithm",
"python",
"traveling_salesman"
] |
stackoverflow_0002185177_algorithm_evolutionary_algorithm_genetic_algorithm_python_traveling_salesman.txt
|
Q:
How to start a local port on user's computer (Edited question)
sorry in the past I have not been able to formulate my question coherently. This will be my last try. =|
Basically, I want to do something like this website is doing: http://www.ninjavideo.net/video/56388. They are rendering an iframe that points to a port on localhost. You will see nothing in the iframe if you dont have their applet running (which can be found here: ninjavideo.net/applet.php ). I want to write a script that does something like what applet.php is doing, but I don't think they are using only php code as it won't run on computers that don't have php installed. Do you suppose they are using Java/C to do this?
Thanks for all your suggestions.
A:
An Applet is basically a piece of Java code which is served by a webpage and is supposed to run at the client machine. You can learn more about Applets at Sun's own Applet tutorial. If you're green to Java as well, then I recommend to go through Trials Covering the Basics first. Opening sockets (ports) using Java code is covered here.
That PHP script is just serving the applet code from the server, so that the client can download it.
A:
You could do this in PHP using a ready-to-run Apache setup (there are some that are ready to run from a USB key, should be possible to make into something that a client can install, but is complicated, see e.g. this tutorial) or a product like NuSphere Dock:
PhpDock is a deployment platform for PHP applications.
PhpDock enables you to deploy any PHP web application as a Stand Alone Windows Desktop application w/o any changes in the code.
PhpDock combines NuSphere's powerful embeded Srv webserver and browser components.
I would usually say that if you are looking to build a Windows application, you should go with a tool that is aimed at just that, i.e. C++, C#, Java, the .NET platform, Delphi, and the likes. But if you need some kind of daemon or local web server, you may actually be well off with a product bringing a web server to the desktop.
|
How to start a local port on user's computer (Edited question)
|
sorry in the past I have not been able to formulate my question coherently. This will be my last try. =|
Basically, I want to do something like this website is doing: http://www.ninjavideo.net/video/56388. They are rendering an iframe that points to a port on localhost. You will see nothing in the iframe if you dont have their applet running (which can be found here: ninjavideo.net/applet.php ). I want to write a script that does something like what applet.php is doing, but I don't think they are using only php code as it won't run on computers that don't have php installed. Do you suppose they are using Java/C to do this?
Thanks for all your suggestions.
|
[
"An Applet is basically a piece of Java code which is served by a webpage and is supposed to run at the client machine. You can learn more about Applets at Sun's own Applet tutorial. If you're green to Java as well, then I recommend to go through Trials Covering the Basics first. Opening sockets (ports) using Java code is covered here.\nThat PHP script is just serving the applet code from the server, so that the client can download it.\n",
"You could do this in PHP using a ready-to-run Apache setup (there are some that are ready to run from a USB key, should be possible to make into something that a client can install, but is complicated, see e.g. this tutorial) or a product like NuSphere Dock:\n\nPhpDock is a deployment platform for PHP applications.\nPhpDock enables you to deploy any PHP web application as a Stand Alone Windows Desktop application w/o any changes in the code.\nPhpDock combines NuSphere's powerful embeded Srv webserver and browser components.\n\nI would usually say that if you are looking to build a Windows application, you should go with a tool that is aimed at just that, i.e. C++, C#, Java, the .NET platform, Delphi, and the likes. But if you need some kind of daemon or local web server, you may actually be well off with a product bringing a web server to the desktop.\n"
] |
[
2,
0
] |
[] |
[] |
[
"c",
"java",
"localhost",
"php",
"python"
] |
stackoverflow_0002185823_c_java_localhost_php_python.txt
|
Q:
Expanding elements in a list
I'm looking for a "nice" way to process a list where some elements need to be expanded into more elements (only once, no expansion on the results).
Standard iterative way would be to do:
i=0
while i < len(l):
if needs_expanding(l[i]):
new_is = expand(l[i])
l[i:i] = new_is
i += len(new_is)
else:
i += 1
which is pretty ugly. I could rewrite the contents into a new list with:
nl = []
for x in l:
if needs_expanding(x):
nl += expand(x)
else:
nl.append(x)
But they both seem too long. Or I could simply do 2 passes and flatten the list later:
flatten(expand(x) if needs_expanding(x) else x for x in l)
# or
def try_expanding(x)....
flatten(try_expanding(x) for x in l)
but this doesn't feel "right" either.
Are there any other clear ways of doing this?
A:
Your last two answers are what I would do. I'm not familiar with flatten() though, but if you have such a function then that looks ideal. You can also use the built-in sum():
sum(expand(x) if needs_expanding(x) else [x] for x in l, [])
sum(needs_expanding(x) and expand(x) or [x] for x in l, [])
A:
The last one is probably your most pythonic, but you could try an implied loop (or in py3, generator) with map:
flatten(map(lambda x: expand(x) if needs_expanding(x) else x, l))
flatten(map(try_expanding, l))
A:
If you do not need random access in the list you are generating, you could also use write a generator.
def iter_new_list(old_list):
for x in old_list:
if needs_expanding(x):
for y in expand(x):
yield y
else:
yield x
new_list = list(iter_new_list(old_list))
This is functionally equivalent to your second example, but it might be more readable in your real-world situation.
Also, Python coding standards forbid the use of lowercase-L as a variable name, as it is nearly indistinguishable from the numeral one.
|
Expanding elements in a list
|
I'm looking for a "nice" way to process a list where some elements need to be expanded into more elements (only once, no expansion on the results).
Standard iterative way would be to do:
i=0
while i < len(l):
if needs_expanding(l[i]):
new_is = expand(l[i])
l[i:i] = new_is
i += len(new_is)
else:
i += 1
which is pretty ugly. I could rewrite the contents into a new list with:
nl = []
for x in l:
if needs_expanding(x):
nl += expand(x)
else:
nl.append(x)
But they both seem too long. Or I could simply do 2 passes and flatten the list later:
flatten(expand(x) if needs_expanding(x) else x for x in l)
# or
def try_expanding(x)....
flatten(try_expanding(x) for x in l)
but this doesn't feel "right" either.
Are there any other clear ways of doing this?
|
[
"Your last two answers are what I would do. I'm not familiar with flatten() though, but if you have such a function then that looks ideal. You can also use the built-in sum():\nsum(expand(x) if needs_expanding(x) else [x] for x in l, [])\nsum(needs_expanding(x) and expand(x) or [x] for x in l, [])\n\n",
"The last one is probably your most pythonic, but you could try an implied loop (or in py3, generator) with map:\nflatten(map(lambda x: expand(x) if needs_expanding(x) else x, l))\nflatten(map(try_expanding, l))\n\n",
"If you do not need random access in the list you are generating, you could also use write a generator.\ndef iter_new_list(old_list): \n for x in old_list:\n if needs_expanding(x):\n for y in expand(x):\n yield y\n else:\n yield x\n\nnew_list = list(iter_new_list(old_list))\n\nThis is functionally equivalent to your second example, but it might be more readable in your real-world situation.\nAlso, Python coding standards forbid the use of lowercase-L as a variable name, as it is nearly indistinguishable from the numeral one.\n"
] |
[
3,
2,
2
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002185822_list_python.txt
|
Q:
Is there a Python module to access Advantage Database Server?
As the title suggest, I was wondering if there is a Python module that can access an Advantage Database Server (Sybase) files such as ADT and DBF.
I have searched the web and couldn't find what I'm looking for this is why I wanted to ask it here.
A:
I have used pyodbc with the Advantage ODBC driver, http://code.google.com/p/pyodbc/ and pywin32 http://sourceforge.net/projects/pywin32/ with the Advantage OLE DB provider successfully. My personal preference is the pyodbc driver.
There is now a native wrapper at http://code.google.com/p/adsdb/.
A:
dbfpy (and many other modules) let you read and write DBF files. I'm not aware of similar modules dealing with ADT files directly, but I think there are converters to make DBF files to/from ADT, if worse comes to worst.
Another alternative for accessing ADT files would be to actually run sybase advantage with its odbc driver -- if that is feasible, there are several ways to connect to an ODBC service with Python.
|
Is there a Python module to access Advantage Database Server?
|
As the title suggest, I was wondering if there is a Python module that can access an Advantage Database Server (Sybase) files such as ADT and DBF.
I have searched the web and couldn't find what I'm looking for this is why I wanted to ask it here.
|
[
"I have used pyodbc with the Advantage ODBC driver, http://code.google.com/p/pyodbc/ and pywin32 http://sourceforge.net/projects/pywin32/ with the Advantage OLE DB provider successfully. My personal preference is the pyodbc driver.\nThere is now a native wrapper at http://code.google.com/p/adsdb/.\n",
"dbfpy (and many other modules) let you read and write DBF files. I'm not aware of similar modules dealing with ADT files directly, but I think there are converters to make DBF files to/from ADT, if worse comes to worst.\nAnother alternative for accessing ADT files would be to actually run sybase advantage with its odbc driver -- if that is feasible, there are several ways to connect to an ODBC service with Python.\n"
] |
[
3,
1
] |
[] |
[] |
[
"advantage_database_server",
"database",
"dbf",
"module",
"python"
] |
stackoverflow_0001189146_advantage_database_server_database_dbf_module_python.txt
|
Q:
Pointers to members in swig (or Boost::Python)
I made some bindings from my C++ app for python.
The problem is that I use pointers to members (It's for computing shortest path and giving the property to minimize as parameter).
This is the C++ signature:
std::vector<Path> martins(int start, int dest, MultimodalGraph & g, float Edge::*)
This is what I did (from what I understood in the doc):
%constant float Edge::* distance = &Edge::distance;
This is how I call my function from python:
foo.martins(0, 1000, g, foo.distance)
And this is the error I get:
NotImplementedError: Wrong number of arguments for overloaded function 'martins'.
Possible C/C++ prototypes are:
martins(int,int,MultimodalGraph &,float Edge::*)
I have an overloaded method that uses a default 4th paramaters, and it works perfectly.
So is it possible to use pointers to members with swig? If yes, what's the trick? If no, what would be the most elegant way to work arround?
Thank you for your help!
UPDATE: if someone knows if Boost::python does it for sure, I'll switch to it.
A:
Don't know about SWIG, but in boost::python you can write a wrapper:
bool foo(int x, float* result);
boost::python::tuple foo_wrapper(int x)
{
float v;
bool result = foo(x, &v);
return boost::python::make_tuple(result, v);
}
BOOST_PYTHON_MODULE(foomodule)
{
def("foo", &foo_wrapper);
}
And in python you would:
result, v = foomodule.foo(x)
Since in Python floats are immutable, you can't actually pass one to a method and expect the method to change the float value, so we adapt the code to return a tuple of values instead.
|
Pointers to members in swig (or Boost::Python)
|
I made some bindings from my C++ app for python.
The problem is that I use pointers to members (It's for computing shortest path and giving the property to minimize as parameter).
This is the C++ signature:
std::vector<Path> martins(int start, int dest, MultimodalGraph & g, float Edge::*)
This is what I did (from what I understood in the doc):
%constant float Edge::* distance = &Edge::distance;
This is how I call my function from python:
foo.martins(0, 1000, g, foo.distance)
And this is the error I get:
NotImplementedError: Wrong number of arguments for overloaded function 'martins'.
Possible C/C++ prototypes are:
martins(int,int,MultimodalGraph &,float Edge::*)
I have an overloaded method that uses a default 4th paramaters, and it works perfectly.
So is it possible to use pointers to members with swig? If yes, what's the trick? If no, what would be the most elegant way to work arround?
Thank you for your help!
UPDATE: if someone knows if Boost::python does it for sure, I'll switch to it.
|
[
"Don't know about SWIG, but in boost::python you can write a wrapper:\nbool foo(int x, float* result);\n\nboost::python::tuple foo_wrapper(int x)\n{\n float v;\n bool result = foo(x, &v);\n return boost::python::make_tuple(result, v);\n}\n\nBOOST_PYTHON_MODULE(foomodule)\n{\n def(\"foo\", &foo_wrapper);\n}\n\nAnd in python you would:\nresult, v = foomodule.foo(x)\n\nSince in Python floats are immutable, you can't actually pass one to a method and expect the method to change the float value, so we adapt the code to return a tuple of values instead.\n"
] |
[
2
] |
[] |
[] |
[
"boost_python",
"c++",
"python",
"swig"
] |
stackoverflow_0001770725_boost_python_c++_python_swig.txt
|
Q:
Google App Engine won't recognize facebook package unless I rename it
I'm trying to intergrate Facebook Connect into an GAE app. I've got a basic folder structure like so:
/gae-root
/myapp
/templates
/etc
app.yaml
settings.py
and I tried to add the PyFacebook library like so:
/gae-root
/myapp
/templates
/etc
/facebook
/djangofb
app.yaml
settings.py
I thought this would work, but now when I try to import facebook it throws a module not found error. What's even weirder is that if I rename the directory from facebook to foo, the import now works but I'll hit errors later when I try to get the current logged in user.
Literally all I did was move the directory into my folder structure and try an import. What am I missing? Sorry if this is an easy question.
A:
It was a problem with an extra .pth file in my site-packages directory.
|
Google App Engine won't recognize facebook package unless I rename it
|
I'm trying to intergrate Facebook Connect into an GAE app. I've got a basic folder structure like so:
/gae-root
/myapp
/templates
/etc
app.yaml
settings.py
and I tried to add the PyFacebook library like so:
/gae-root
/myapp
/templates
/etc
/facebook
/djangofb
app.yaml
settings.py
I thought this would work, but now when I try to import facebook it throws a module not found error. What's even weirder is that if I rename the directory from facebook to foo, the import now works but I'll hit errors later when I try to get the current logged in user.
Literally all I did was move the directory into my folder structure and try an import. What am I missing? Sorry if this is an easy question.
|
[
"It was a problem with an extra .pth file in my site-packages directory.\n"
] |
[
0
] |
[] |
[] |
[
"facebook",
"google_app_engine",
"python"
] |
stackoverflow_0002062504_facebook_google_app_engine_python.txt
|
Q:
wxPython GUI: migrating gnuplot to matplotlib
I currently have a GUI built in wxPython with several sections, one of which displays a .png image of a plot:
self.plot = wx.BitmapButton(self.pane_system, -1, wx.Bitmap("/home/myname/projects/newton/plot/src/graph.png", wx.BITMAP_TYPE_ANY))
In another part of the GUI, there is a place where I can edit parameters. The current setup is that When I change the parameters and press enter, the code tells Gnuplot to re-plot and save the new plot to the graph.png file, then update the GUI to show the updated image.
I have several general questions:
I want to migrate gnuplot to matplotlib for the following reason: If I use gnuplot, the machine that is running the executable must have gnuplot installed on their machine. On the other hand, matplotlib is a python module, so I don't have to worry about installing graphical packages on the other machines. Is this assumption correct?
How can I modify my wxPython GUI window to show the matplotlib plot? I found tutorials several telling me how to create a new panel with a matplotlib plot, but I would like to simply have it appear where the old plot was. I think I can make matplotlib save the plot to an image file just as I did in gnuplot. Is it generally a good idea to save the plot as an image and update the GUI, or are there other (faster) best practices for updating plots? One drawback of using image files (as in the above code) is that they do not resize when I resize the GUI window.
If I package this as an executable, will I have to install wxPython/Python on a Windows machine to make the executable run?
A:
Taking your questions in order:
1.) Yes matplotlib is a contained python module. It does have external dependancies but in Windows these dependencies are packaged with the matplotlib install. Do you need to worry about these when you install on other machines? That depends on how you are going to install. Are you packing to an exe? Having the end users install Python and matplotlib? As an example you can package matplotlib into your exe with py2exe, see here. Of course you'll have to customize those scripts for your backend, wx.
2.) You are seeing the panels with plots because matplotlib provides the FigureCanvasWxAgg, which is a wxWidget derived from wxPanel that plays nice with matplotlib. The advantages of using it are that you can set handlers for stuff like resize and painting.
Your wxBitMapButton, though is looking for a wxBitmap for the image. You might be able to give it a file handle (cStringIO.StringIO) to a matplotlib plot and eliminate the need to write a file to disk. You also could probably hook it's resize event and get matplotlib to redraw the figure to the appropriate size. You aren't going to have the amount of flexibility as using the FigureCanvasWxAgg. I can't research any of this, though, as it seems the wxPython web-site is down.
3.) You can package wxPython into executable. How depends on what packager you are using. I've done this with py2exe many times.
|
wxPython GUI: migrating gnuplot to matplotlib
|
I currently have a GUI built in wxPython with several sections, one of which displays a .png image of a plot:
self.plot = wx.BitmapButton(self.pane_system, -1, wx.Bitmap("/home/myname/projects/newton/plot/src/graph.png", wx.BITMAP_TYPE_ANY))
In another part of the GUI, there is a place where I can edit parameters. The current setup is that When I change the parameters and press enter, the code tells Gnuplot to re-plot and save the new plot to the graph.png file, then update the GUI to show the updated image.
I have several general questions:
I want to migrate gnuplot to matplotlib for the following reason: If I use gnuplot, the machine that is running the executable must have gnuplot installed on their machine. On the other hand, matplotlib is a python module, so I don't have to worry about installing graphical packages on the other machines. Is this assumption correct?
How can I modify my wxPython GUI window to show the matplotlib plot? I found tutorials several telling me how to create a new panel with a matplotlib plot, but I would like to simply have it appear where the old plot was. I think I can make matplotlib save the plot to an image file just as I did in gnuplot. Is it generally a good idea to save the plot as an image and update the GUI, or are there other (faster) best practices for updating plots? One drawback of using image files (as in the above code) is that they do not resize when I resize the GUI window.
If I package this as an executable, will I have to install wxPython/Python on a Windows machine to make the executable run?
|
[
"Taking your questions in order:\n1.) Yes matplotlib is a contained python module. It does have external dependancies but in Windows these dependencies are packaged with the matplotlib install. Do you need to worry about these when you install on other machines? That depends on how you are going to install. Are you packing to an exe? Having the end users install Python and matplotlib? As an example you can package matplotlib into your exe with py2exe, see here. Of course you'll have to customize those scripts for your backend, wx.\n2.) You are seeing the panels with plots because matplotlib provides the FigureCanvasWxAgg, which is a wxWidget derived from wxPanel that plays nice with matplotlib. The advantages of using it are that you can set handlers for stuff like resize and painting.\nYour wxBitMapButton, though is looking for a wxBitmap for the image. You might be able to give it a file handle (cStringIO.StringIO) to a matplotlib plot and eliminate the need to write a file to disk. You also could probably hook it's resize event and get matplotlib to redraw the figure to the appropriate size. You aren't going to have the amount of flexibility as using the FigureCanvasWxAgg. I can't research any of this, though, as it seems the wxPython web-site is down.\n3.) You can package wxPython into executable. How depends on what packager you are using. I've done this with py2exe many times.\n"
] |
[
2
] |
[] |
[] |
[
"matplotlib",
"python",
"wxpython"
] |
stackoverflow_0002186240_matplotlib_python_wxpython.txt
|
Q:
how to check if request is ajax in turbogears
How do I go about checking if a request is an ajax request in a controller method in Turbogears? Further, is it possible to return a 'partial' much like in rails or symfony if the request is an ajax request. I know about the json decorator but I need a way to return a partial of a mako template (because I need to format the data and don't want to to do it all in Javascript). For example if I want to return the formatted list for page two of a list of news stories, I do not want to return the entire page (but rather just the formatted list).
Thanks
A:
jQuery, YUI, Prototype, Dojo, and MooTools all set the header X-Requested-With: XMLHttpRequest. You should be able to check for that header.
|
how to check if request is ajax in turbogears
|
How do I go about checking if a request is an ajax request in a controller method in Turbogears? Further, is it possible to return a 'partial' much like in rails or symfony if the request is an ajax request. I know about the json decorator but I need a way to return a partial of a mako template (because I need to format the data and don't want to to do it all in Javascript). For example if I want to return the formatted list for page two of a list of news stories, I do not want to return the entire page (but rather just the formatted list).
Thanks
|
[
"jQuery, YUI, Prototype, Dojo, and MooTools all set the header X-Requested-With: XMLHttpRequest. You should be able to check for that header.\n"
] |
[
1
] |
[] |
[] |
[
"ajax",
"mako",
"python",
"turbogears2"
] |
stackoverflow_0002187115_ajax_mako_python_turbogears2.txt
|
Q:
Manage Increasingly complex Django URL views efficiently? (urls.py)
So, I have this Django application and I keep adding new features to provide ever more granular views of the data. To give a quick idea of the problem, here's a subset of urls.py:
# Simple enough . . .
(r'^$', 'index'),
(r'^date/(?P<year>\d{4})$', 'index'),
(r'^date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index'),
(r'^date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$', 'index'),
(r'^page/(?P<page>\d+)$', 'index'),
So, yeah, the default view, date views, a paginated view, then a similar setup for user-specific URLs:
# user
(r'^user/(?P<username>\w+)$', 'index_username'),
(r'^user/(?P<username>\w+)/date/(?P<year>\d{4})$', 'index_username'),
(r'^user/(?P<username>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index_username'),
(r'^user/(?P<username>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$', 'index_username'),
(r'^user/(?P<username>\w+)/page/(?P<page>\d+)$', 'index_username'),
Then, similar again for Teams . . .
# Team View
(r'^team/(?P<team>\w+)$', 'index'),
(r'^team/(?P<team>\w+)/date/(?P<year>\d{4})$', 'index'),
(r'^team/(?P<team>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index'),
(r'^team/(?P<team>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$', 'index'),
(r'^team/(?P<team>\w+)/page/(?P<page>\d+)$', 'index'),
Now, I want to add a "search" view, and really I think it'd be nice to just add that to the end of many of the above URLs, so I could hit something like:
/search/foo
/user/fred/date/2010-01/search/baz
And then I could just pass a search parameter to the view, which could constrains the results appropriately.
But say, if I want to apply that to the user, team, and by-date views, I've got what 12 new lines added to urls.py. And each time I add another potential view option (say, paginated search results?) . . . it just feels like there ought to be a better way.
From my research, the answer would seem to be:
1) Broader matching within urls.py and have the view function parse the query string.
2) Maybe some beefier regular expression logic in urls.py that can say "if this pattern matches, include the parameter when passing to the view function" multiple times. But that's possibly nightmarish to maintain.
Has anyone conjured a wiser solution to managing complex URLs elegantly? I'm thinking that at a certain point it is cleanest simply to pass the parameter-matching logic to the view itself, to parse parameters out of the query string. So, near the top of the view I might have some code that looks like this:
# Date Queries
re_ymd = re.compile('date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})')
re_ym = re.compile('date/(?P<year>\d{4})-(?P<month>\d{2})')
re_y = re.compile('date/(?P<year>\d{4})')
if( re_ymd.search(qs) ):
year = re_ymd.search(qs).group('year')
month = re_ymd.search(qs).group('month')
day = re_ymd.search(qs).group('day')
elif( re_ym.search(qs) ):
year = re_ym.search(qs).group('year')
month = re_ym.search(qs).group('month')
elif( re_y.search(qs) ):
year = re_y.search(qs).group('year')
# Pagination queries
re_p = re.compile('page/(?P<page>\d+)')
if( re_p.search(qs) ):
page = re_p.search(qs).group('page')
# Search queries
re_s = re.compile('search/(?P<search>\w+)')
if( re_s.search(qs) ):
search = re_s.search(qs).group('search')
So, is that the clever way of reducing the repetetive complexity I have been introducing to urls.py?
A:
Why not use GET parameters, or django-filter, if all you do is just filter/group the results differently?
The reasons I see for using GET are that its easier to implement, and seems a little cleaner: in the URL solution /search/foo/user/bar/ and /user/bar/search/foo/ are 2 names for the exact same content. In the GET parameters solution its all the same page.
A:
Let's focus on this one:
# Simple enough . . .
(r'^$', 'index'),
(r'^date/(?P<year>\d{4})$', 'index'),
(r'^date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index'),
(r'^date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$', 'index'),
(r'^page/(?P<page>\d+)$', 'index'),
I assume that there is some:
def index(year=2010, month=2, day=2, page=0):
# whatever
So, why don't you combine you regexes in one, e.g.
r'^date/(?P<year>\d{4})(-(?P<month>\d{2})(-(?P<day>\d{2}))?)?$
I haven't tried it, but I'm pretty sure something like this would work.
EDIT:
While re-writing regexes could work, take a look at Ofri Raviv's answer because it could be that you have some meta-problem here.
|
Manage Increasingly complex Django URL views efficiently? (urls.py)
|
So, I have this Django application and I keep adding new features to provide ever more granular views of the data. To give a quick idea of the problem, here's a subset of urls.py:
# Simple enough . . .
(r'^$', 'index'),
(r'^date/(?P<year>\d{4})$', 'index'),
(r'^date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index'),
(r'^date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$', 'index'),
(r'^page/(?P<page>\d+)$', 'index'),
So, yeah, the default view, date views, a paginated view, then a similar setup for user-specific URLs:
# user
(r'^user/(?P<username>\w+)$', 'index_username'),
(r'^user/(?P<username>\w+)/date/(?P<year>\d{4})$', 'index_username'),
(r'^user/(?P<username>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index_username'),
(r'^user/(?P<username>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$', 'index_username'),
(r'^user/(?P<username>\w+)/page/(?P<page>\d+)$', 'index_username'),
Then, similar again for Teams . . .
# Team View
(r'^team/(?P<team>\w+)$', 'index'),
(r'^team/(?P<team>\w+)/date/(?P<year>\d{4})$', 'index'),
(r'^team/(?P<team>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})$', 'index'),
(r'^team/(?P<team>\w+)/date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$', 'index'),
(r'^team/(?P<team>\w+)/page/(?P<page>\d+)$', 'index'),
Now, I want to add a "search" view, and really I think it'd be nice to just add that to the end of many of the above URLs, so I could hit something like:
/search/foo
/user/fred/date/2010-01/search/baz
And then I could just pass a search parameter to the view, which could constrains the results appropriately.
But say, if I want to apply that to the user, team, and by-date views, I've got what 12 new lines added to urls.py. And each time I add another potential view option (say, paginated search results?) . . . it just feels like there ought to be a better way.
From my research, the answer would seem to be:
1) Broader matching within urls.py and have the view function parse the query string.
2) Maybe some beefier regular expression logic in urls.py that can say "if this pattern matches, include the parameter when passing to the view function" multiple times. But that's possibly nightmarish to maintain.
Has anyone conjured a wiser solution to managing complex URLs elegantly? I'm thinking that at a certain point it is cleanest simply to pass the parameter-matching logic to the view itself, to parse parameters out of the query string. So, near the top of the view I might have some code that looks like this:
# Date Queries
re_ymd = re.compile('date/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})')
re_ym = re.compile('date/(?P<year>\d{4})-(?P<month>\d{2})')
re_y = re.compile('date/(?P<year>\d{4})')
if( re_ymd.search(qs) ):
year = re_ymd.search(qs).group('year')
month = re_ymd.search(qs).group('month')
day = re_ymd.search(qs).group('day')
elif( re_ym.search(qs) ):
year = re_ym.search(qs).group('year')
month = re_ym.search(qs).group('month')
elif( re_y.search(qs) ):
year = re_y.search(qs).group('year')
# Pagination queries
re_p = re.compile('page/(?P<page>\d+)')
if( re_p.search(qs) ):
page = re_p.search(qs).group('page')
# Search queries
re_s = re.compile('search/(?P<search>\w+)')
if( re_s.search(qs) ):
search = re_s.search(qs).group('search')
So, is that the clever way of reducing the repetetive complexity I have been introducing to urls.py?
|
[
"Why not use GET parameters, or django-filter, if all you do is just filter/group the results differently?\nThe reasons I see for using GET are that its easier to implement, and seems a little cleaner: in the URL solution /search/foo/user/bar/ and /user/bar/search/foo/ are 2 names for the exact same content. In the GET parameters solution its all the same page.\n",
"Let's focus on this one:\n # Simple enough . . .\n (r'^$', 'index'),\n (r'^date/(?P<year>\\d{4})$', 'index'),\n (r'^date/(?P<year>\\d{4})-(?P<month>\\d{2})$', 'index'),\n (r'^date/(?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})$', 'index'),\n (r'^page/(?P<page>\\d+)$', 'index'),\n\nI assume that there is some:\n def index(year=2010, month=2, day=2, page=0):\n # whatever\n\nSo, why don't you combine you regexes in one, e.g.\n r'^date/(?P<year>\\d{4})(-(?P<month>\\d{2})(-(?P<day>\\d{2}))?)?$\n\nI haven't tried it, but I'm pretty sure something like this would work.\nEDIT:\nWhile re-writing regexes could work, take a look at Ofri Raviv's answer because it could be that you have some meta-problem here.\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"django_urls",
"python"
] |
stackoverflow_0002187273_django_django_urls_python.txt
|
Q:
Making a module global?
I would like to know why
>>> def func2():
... global time
... import time
...
>>> time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
>>> func2()
>>> time
<module 'time' (built-in)>
>>>
works, but
>>> def func():
... global module
... module="time"
... exec ("global %s" %module)
... exec ("import %s" %module)
...
>>> time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
>>> func()
>>> time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
works not, and how i could get it to work =)
thank you
A:
Each of your exec() calls happens in a separate namespace. Abandon this path; it will only lead to ruin.
A:
Because exec uses its own scope by default. If you do exec "global {0}; import {0}".format(module) in globals(), then it'll work.
You shouldn't be doing that, unless you really need to.
A:
To import a module given the name as a string use
time=__import__('time')
Here's one way you might use it
usermodulenames = ["foo","bar","baz"]
usermodules = dict((k,__import__(k)) for k in usermodulenames)
A:
What you are trying to do is either very sophisticated or very odd. This is how it works:
exec ("import %s" % module) in globals()
Please describe the bigger problem you are trying to solve
|
Making a module global?
|
I would like to know why
>>> def func2():
... global time
... import time
...
>>> time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
>>> func2()
>>> time
<module 'time' (built-in)>
>>>
works, but
>>> def func():
... global module
... module="time"
... exec ("global %s" %module)
... exec ("import %s" %module)
...
>>> time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
>>> func()
>>> time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
works not, and how i could get it to work =)
thank you
|
[
"Each of your exec() calls happens in a separate namespace. Abandon this path; it will only lead to ruin.\n",
"Because exec uses its own scope by default. If you do exec \"global {0}; import {0}\".format(module) in globals(), then it'll work.\nYou shouldn't be doing that, unless you really need to.\n",
"To import a module given the name as a string use\ntime=__import__('time')\n\nHere's one way you might use it\nusermodulenames = [\"foo\",\"bar\",\"baz\"]\nusermodules = dict((k,__import__(k)) for k in usermodulenames)\n\n",
"What you are trying to do is either very sophisticated or very odd. This is how it works:\nexec (\"import %s\" % module) in globals()\n\nPlease describe the bigger problem you are trying to solve\n"
] |
[
7,
1,
1,
0
] |
[] |
[] |
[
"global",
"module",
"python"
] |
stackoverflow_0002187381_global_module_python.txt
|
Q:
proxy-like python module
Can a python module hand over other module in case of self being imported?
A:
You can sort of do it (in the normal CPython anyway):
# uglyhack.py
import sys
import othermodule
sys.modules[__name__]= othermodule
then:
>>> import uglyhack
>>> uglyhack
<module 'othermodule' from '...'>
This relies on the assignment of the global for the module in the importing script/module happening after the body of imported module has finished executing, so by the time the import assignment happens, the sys.modules lookup has been sabotaged to point at another module.
I wouldn't use this in proper code for anything other than (maybe) debugging. There should almost always be a better way for whatever it is you're up to.
A:
import other_module
for name in dir(other_module):
globals()[name] = getattr(other_module, name)
del other_module
|
proxy-like python module
|
Can a python module hand over other module in case of self being imported?
|
[
"You can sort of do it (in the normal CPython anyway):\n# uglyhack.py\n\nimport sys\nimport othermodule\n\nsys.modules[__name__]= othermodule\n\nthen:\n>>> import uglyhack\n>>> uglyhack\n<module 'othermodule' from '...'>\n\nThis relies on the assignment of the global for the module in the importing script/module happening after the body of imported module has finished executing, so by the time the import assignment happens, the sys.modules lookup has been sabotaged to point at another module.\nI wouldn't use this in proper code for anything other than (maybe) debugging. There should almost always be a better way for whatever it is you're up to.\n",
"import other_module\nfor name in dir(other_module):\n globals()[name] = getattr(other_module, name)\ndel other_module\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002186977_python.txt
|
Q:
python 2.6 cPickle.load results in EOFError
I use cPickle to pickle a list of integers, using HIGHEST_PROTOCOL,
cPickle.dump(l, f, HIGHEST_PROTOCOL)
When I try to unpickle this using the following code, I get an EOFError. I tried 'seeking' to offset 0 before unpickling, but the error persists.
l = cPickle.load(f)
Any ideas?
A:
If you are on windows, make sure you
open(filename, 'wb') # for writing
open(filename, 'rb') # for reading
|
python 2.6 cPickle.load results in EOFError
|
I use cPickle to pickle a list of integers, using HIGHEST_PROTOCOL,
cPickle.dump(l, f, HIGHEST_PROTOCOL)
When I try to unpickle this using the following code, I get an EOFError. I tried 'seeking' to offset 0 before unpickling, but the error persists.
l = cPickle.load(f)
Any ideas?
|
[
"If you are on windows, make sure you \nopen(filename, 'wb') # for writing\nopen(filename, 'rb') # for reading\n\n"
] |
[
20
] |
[] |
[] |
[
"eoferror",
"pickle",
"python"
] |
stackoverflow_0002187558_eoferror_pickle_python.txt
|
Q:
How can I render a Django template that has UTF8 characters in it?
I'm trying to send a django email with UTF-8 characters in the template, specifically:
S'il vous plaît
I get the error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 147: unexpected code byte
When trying to encode the special "î" character (that is the character at that position.)
Here is my code for generating the email body:
template = loader.get_template('french_thank_you.html')
A:
The editor you're using has saved the file using Mac Roman encoding. Open the template, re-save it as UTF-8, and it should work fine.
A:
0x94 is not part of î in UTF-8. The UTF-8 encoding for î is 0xc3 0xae.
|
How can I render a Django template that has UTF8 characters in it?
|
I'm trying to send a django email with UTF-8 characters in the template, specifically:
S'il vous plaît
I get the error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 147: unexpected code byte
When trying to encode the special "î" character (that is the character at that position.)
Here is my code for generating the email body:
template = loader.get_template('french_thank_you.html')
|
[
"The editor you're using has saved the file using Mac Roman encoding. Open the template, re-save it as UTF-8, and it should work fine.\n",
"0x94 is not part of î in UTF-8. The UTF-8 encoding for î is 0xc3 0xae.\n"
] |
[
6,
1
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0002187561_django_django_templates_python.txt
|
Q:
What's the python __all__ module level variable for?
I've seen it a lot in python/Lib source code but I don't know what it is for.
I thought it was used to limit accessible members of of a module. So only the elements at __all__ will show up when dir(module).
I did a little example and saw it was not working as I expected.
So... What's the python __all__ module level variable for?
A:
It has two purposes:
Anybody who reads the source will know what the exposed public API is. It doesn't prevent them from poking around in private declarations, but does provide a good warning not to.
When using from mod import *, only names listed in __all__ will be imported. This is not as important, in my opinion, because importing everything is a really bad idea.
A:
http://docs.python.org/tutorial/modules.html#importing-from-a-package
Now what happens when the user writes
from sound.effects import *? Ideally,
one would hope that this somehow goes
out to the filesystem, finds which
submodules are present in the package,
and imports them all. This could take
a long time and importing sub-modules
might have unwanted side-effects that
should only happen when the sub-module
is explicitly imported.
The only solution is for the package
author to provide an explicit index of
the package. The import statement uses
the following convention: if a
package’s __init__.py code defines a
list named __all__, it is taken to be
the list of module names that should
be imported when from package import *
is encountered. It is up to the
package author to keep this list
up-to-date when a new version of the
package is released. Package authors
may also decide not to support it, if
they don’t see a use for importing *
from their package.
A:
It controls what you get pulled into your namepsace when you
from blah import *
See Importing * from a Package
|
What's the python __all__ module level variable for?
|
I've seen it a lot in python/Lib source code but I don't know what it is for.
I thought it was used to limit accessible members of of a module. So only the elements at __all__ will show up when dir(module).
I did a little example and saw it was not working as I expected.
So... What's the python __all__ module level variable for?
|
[
"It has two purposes:\n\nAnybody who reads the source will know what the exposed public API is. It doesn't prevent them from poking around in private declarations, but does provide a good warning not to.\nWhen using from mod import *, only names listed in __all__ will be imported. This is not as important, in my opinion, because importing everything is a really bad idea.\n\n",
"http://docs.python.org/tutorial/modules.html#importing-from-a-package\n\nNow what happens when the user writes\n from sound.effects import *? Ideally,\n one would hope that this somehow goes\n out to the filesystem, finds which\n submodules are present in the package,\n and imports them all. This could take\n a long time and importing sub-modules\n might have unwanted side-effects that\n should only happen when the sub-module\n is explicitly imported.\nThe only solution is for the package\n author to provide an explicit index of\n the package. The import statement uses\n the following convention: if a\n package’s __init__.py code defines a\n list named __all__, it is taken to be\n the list of module names that should\n be imported when from package import *\n is encountered. It is up to the\n package author to keep this list\n up-to-date when a new version of the\n package is released. Package authors\n may also decide not to support it, if\n they don’t see a use for importing *\n from their package.\n\n",
"It controls what you get pulled into your namepsace when you \nfrom blah import *\n\nSee Importing * from a Package\n"
] |
[
52,
8,
4
] |
[] |
[] |
[
"namespaces",
"python"
] |
stackoverflow_0002187583_namespaces_python.txt
|
Q:
Python Decorator 3.0 and arguments to the decorator
I'm excited to see the latest version of the decorator python module (3.0). It looks a lot cleaner (e.g. the syntax is more sugary than ever) than previous iterations.
However, it seems to have lousy support (e.g. "sour" syntax, to horribly stretch the metaphor) for decorators that take arguments themselves. Does anyone have a good example for how you'd cleanly do this using decorator 3.0?
def substitute_args(fun, arg_sub_dict):
def wrapper(arg):
new_arg = arg_sub_dict.get(arg, arg)
return fun(new_arg)
# some magic happens here to make sure that type signature,
# __name__, __doc__, etc. of wrapper matches fun
return wrapper
A:
In this case, you need to make your function return the decorator. (Anything can be solved by another level of indirection...)
from decorator import decorator
def substitute_args(arg_sub_dict):
@decorator
def wrapper(fun, arg):
new_arg = arg_sub_dict.get(arg, arg)
return fun(new_arg)
return wrapper
This means substitute_args isn't a decorator itself, it's a decorator factory. Here's the equivalent without the decorator module.
def substitute_args(arg_sub_dict):
def my_decorator(fun):
def wrapper(arg):
new_arg = arg_sub_dict.get(arg, arg)
return fun(new_arg)
# magic to update __name__, etc.
return wrapper
return my_decorator
Three levels deep isn't very convenient, but remember two of them are when the function is defined:
@substitute_args({}) # this function is called and return value is the decorator
def f(x):
return x
# that (anonymous) decorator is applied to f
Which is equivalent to:
def f(x):
return x
f = substitude_args({})(f) # notice the double call
|
Python Decorator 3.0 and arguments to the decorator
|
I'm excited to see the latest version of the decorator python module (3.0). It looks a lot cleaner (e.g. the syntax is more sugary than ever) than previous iterations.
However, it seems to have lousy support (e.g. "sour" syntax, to horribly stretch the metaphor) for decorators that take arguments themselves. Does anyone have a good example for how you'd cleanly do this using decorator 3.0?
def substitute_args(fun, arg_sub_dict):
def wrapper(arg):
new_arg = arg_sub_dict.get(arg, arg)
return fun(new_arg)
# some magic happens here to make sure that type signature,
# __name__, __doc__, etc. of wrapper matches fun
return wrapper
|
[
"In this case, you need to make your function return the decorator. (Anything can be solved by another level of indirection...)\nfrom decorator import decorator\ndef substitute_args(arg_sub_dict):\n @decorator\n def wrapper(fun, arg):\n new_arg = arg_sub_dict.get(arg, arg)\n return fun(new_arg)\n return wrapper\n\nThis means substitute_args isn't a decorator itself, it's a decorator factory. Here's the equivalent without the decorator module.\ndef substitute_args(arg_sub_dict):\n def my_decorator(fun):\n def wrapper(arg):\n new_arg = arg_sub_dict.get(arg, arg)\n return fun(new_arg)\n # magic to update __name__, etc.\n return wrapper\n return my_decorator\n\nThree levels deep isn't very convenient, but remember two of them are when the function is defined:\n@substitute_args({}) # this function is called and return value is the decorator\ndef f(x):\n return x\n# that (anonymous) decorator is applied to f\n\nWhich is equivalent to:\ndef f(x):\n return x\nf = substitude_args({})(f) # notice the double call\n\n"
] |
[
8
] |
[
"here is another way i have just discovered: check whether the first (and only) argument to your decorator is callable; if so, you are done and can return your behavior-modifying wrapper method (itself decorated with functools.wraps to preserve name and documentation string). \nin the other case, one or more named or positional arguments should be present; you can collect those arguments and return a callable that accepts a callable as first argument and returns a wrapper method—and since that description fits the description of the decorator method, return that very decorator method! i’ve used functools.partial here to get a version of my decorator, is_global_method (which i’m working on right now—its implementation is of course nonsense as shown below, this is only to demonstrate the decoration works).\nthis solution appears to work but sure needs more testing. if you quint our eyes, you can see that the trick is only three or four lines as a pattern to remember. now i wonder whether i can wrap that kind of functionality into another decorator? ah, the metaness of it! \nfrom functools import wraps\nfrom functools import partial\n\n_ = print\nis_instance_of = isinstance\nis_callable = lambda x: hasattr( x, '__call__' )\n\ndef is_global_method( x, *, name = None ):\n if is_callable( x ):\n @wraps( x )\n def wrapper( *P, **Q ):\n return { 'name': name, 'result': x( *P, **Q ), }\n return wrapper\n # assert is_instance_of( x, str ) # could do some sanity checks here\n return partial( is_global_method, name = x )\n\n@is_global_method\ndef f( x ):\n \"\"\"This is method f.\"\"\"\n return x ** 2\n\n@is_global_method( 'foobar' )\ndef g( x ):\n \"\"\"This is method g.\"\"\"\n return x ** 2\n\n_( f.__name__ )\n_( f.__doc__ )\n_( f( 42 ) )\n_( g.__name__ )\n_( g.__doc__ )\n_( g( 42 ) )\n\n"
] |
[
-2
] |
[
"decorator",
"python"
] |
stackoverflow_0001060193_decorator_python.txt
|
Q:
Python: how to inherit from two classes?
First of all I'm a python newbie.
I'm playing with Django and I'm trying to extend some classes.
Now I'm in this situation:
I have a new class
customBaseModelAdmin(admin.options.BaseModelAdmin):
#override a method of BaseModelAdmin
and I want to write another class
customModelAdmin(customBaseModelAdmin):
that obviously inherits customBaseModelAdmin, but that has the same methods of the standard ModelAdmin.
But, since the standard ModelAdmin inherits the standard BaseModelAdmin, how can I do?
I tried with the definition
class customModelAdmin(customBaseModelAdmin, admin.options.ModelAdmin):
but it doesn't work.
Do you have any suggestion?
Thanks,
Giovanni
A:
Why not just subclass ModelAdmin for customBaseModelAdmin?
A:
Just let customBaseModelAdmin inherit from ModelAdmin. You can still override the method from BaseModelAdmin.
But of course it could be that ModelAdmin also overrides this method. I would take a look at the source code of these classes to really know what is going on there.
A:
You do it like this:
class customModelAdmin(customBaseModelAdmin):
etc
|
Python: how to inherit from two classes?
|
First of all I'm a python newbie.
I'm playing with Django and I'm trying to extend some classes.
Now I'm in this situation:
I have a new class
customBaseModelAdmin(admin.options.BaseModelAdmin):
#override a method of BaseModelAdmin
and I want to write another class
customModelAdmin(customBaseModelAdmin):
that obviously inherits customBaseModelAdmin, but that has the same methods of the standard ModelAdmin.
But, since the standard ModelAdmin inherits the standard BaseModelAdmin, how can I do?
I tried with the definition
class customModelAdmin(customBaseModelAdmin, admin.options.ModelAdmin):
but it doesn't work.
Do you have any suggestion?
Thanks,
Giovanni
|
[
"Why not just subclass ModelAdmin for customBaseModelAdmin?\n",
"Just let customBaseModelAdmin inherit from ModelAdmin. You can still override the method from BaseModelAdmin.\nBut of course it could be that ModelAdmin also overrides this method. I would take a look at the source code of these classes to really know what is going on there.\n",
"You do it like this:\nclass customModelAdmin(customBaseModelAdmin):\n etc\n\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002187899_django_python.txt
|
Q:
Named arguments: C# vs Python
Both C# and Python allow named arguments, so you can write something like: foo(bar:1). This is great, especially in combination with optional arguments.
My question is: what are the differences between the C# and Python named arguments, if any? I'm not interested in which is the "best", but in whether there are differences and in the possible motivations behind these differences.
And if someone knows of differences with other languages' implementations of this feature (Ruby or Objective-C, maybe), that could be interesting too.
edited to make community-wiki
A:
Python lets you "catch" unspecified named arguments into a dict, which is pretty handy
>>> def f(**kw):
... print kw
...
>>> f(size=3, sides=6, name="hexagon")
{'sides': 6, 'name': 'hexagon', 'size': 3}
A:
Python not only lets you catch unspecified named arguments into a dict, but also lets you unpack a dict into arguments:
>>> def f(alfa, beta, gamma):
... print alfa, beta, gamma
...
>>> f(**{'alfa': 1, 'beta': 2, 'gamma': 3})
1 2 3
and pass them down the stream:
>>> def g(**kwargs):
... f(**kwargs)
...
>>> g(**{'alfa': 1, 'beta': 2, 'gamma': 3})
1 2 3
|
Named arguments: C# vs Python
|
Both C# and Python allow named arguments, so you can write something like: foo(bar:1). This is great, especially in combination with optional arguments.
My question is: what are the differences between the C# and Python named arguments, if any? I'm not interested in which is the "best", but in whether there are differences and in the possible motivations behind these differences.
And if someone knows of differences with other languages' implementations of this feature (Ruby or Objective-C, maybe), that could be interesting too.
edited to make community-wiki
|
[
"Python lets you \"catch\" unspecified named arguments into a dict, which is pretty handy\n>>> def f(**kw):\n... print kw\n... \n>>> f(size=3, sides=6, name=\"hexagon\")\n{'sides': 6, 'name': 'hexagon', 'size': 3}\n\n",
"Python not only lets you catch unspecified named arguments into a dict, but also lets you unpack a dict into arguments:\n >>> def f(alfa, beta, gamma):\n ... print alfa, beta, gamma\n ...\n >>> f(**{'alfa': 1, 'beta': 2, 'gamma': 3})\n 1 2 3\n\nand pass them down the stream:\n >>> def g(**kwargs):\n ... f(**kwargs)\n ...\n >>> g(**{'alfa': 1, 'beta': 2, 'gamma': 3})\n 1 2 3\n\n"
] |
[
6,
5
] |
[] |
[] |
[
"c#",
"keyword_argument",
"python"
] |
stackoverflow_0002187921_c#_keyword_argument_python.txt
|
Q:
entropy in txt file
I have a text file with numbers in it as follows:
1231313123123123
1432423432535345
3532523452345345
1231423432453455
3434535345345345
3452353453253453
all the lines are the same length, I want to calculate entropy on each line and have output as:
2.64234234
2.65464564
2.35355435
etc.
Right now with this piece of code I have gives me entropy to be the same, what am I doing wrong?
Thanks.
#!/usr/bin/env python
import math
def H(data):
if not data:
return 0
entropy = 0
for x in range(256):
p_x = float(data.count(chr(x)))/len(data)
if p_x > 0:
entropy += - p_x*math.log(p_x, 2)
return entropy
failas = open('text.txt', 'r')
for row in failas:
print H('failas')
A:
failas = open('text.txt', 'r')
for row in failas:
print H(row)
A:
Perhaps you meant print H(row).
A:
All of the above, plus you probably don't want to include the \n at end of each line in the entropy calculation. Use H(row.rstrip('\n'))
You can answer a lot of your own questions by examining the data that is being tosssed around by your code. In this case, inserting print repr(data) after the line def H(data): would have shown you what the problem was straight away.
|
entropy in txt file
|
I have a text file with numbers in it as follows:
1231313123123123
1432423432535345
3532523452345345
1231423432453455
3434535345345345
3452353453253453
all the lines are the same length, I want to calculate entropy on each line and have output as:
2.64234234
2.65464564
2.35355435
etc.
Right now with this piece of code I have gives me entropy to be the same, what am I doing wrong?
Thanks.
#!/usr/bin/env python
import math
def H(data):
if not data:
return 0
entropy = 0
for x in range(256):
p_x = float(data.count(chr(x)))/len(data)
if p_x > 0:
entropy += - p_x*math.log(p_x, 2)
return entropy
failas = open('text.txt', 'r')
for row in failas:
print H('failas')
|
[
"failas = open('text.txt', 'r')\nfor row in failas:\n print H(row)\n\n",
"Perhaps you meant print H(row).\n",
"All of the above, plus you probably don't want to include the \\n at end of each line in the entropy calculation. Use H(row.rstrip('\\n'))\nYou can answer a lot of your own questions by examining the data that is being tosssed around by your code. In this case, inserting print repr(data) after the line def H(data): would have shown you what the problem was straight away.\n"
] |
[
10,
5,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002185862_python.txt
|
Q:
How can I view the contents of an array within controller directly for debugging?
I'm just getting started with pylons, and am trying to figure out how to view the contents of variables for debugging without rendering the template.
For example:
class IndexController(BaseController):
def index(self):
# Return a rendered template
#return render('/index.mako')
# or, return a response
return render('/index.mako' )
def test(self):
v = request.params
return v
I would like to view the contents of array v, but I can't figure out how to do it !!
Thanks.
A:
You can use cgitb to debug web applications, it can output detailed tracebacks to files, including variables contents. Here is an article detailing how to use it.
If you can see the server stdout you can also simply print the variable, or else write it to a file: open("my-debug-log.txt", "w").write(repr(variable)). pprint can help making complex data structures (nested arrays, complex dicts, etc...) easier to read in this case.
|
How can I view the contents of an array within controller directly for debugging?
|
I'm just getting started with pylons, and am trying to figure out how to view the contents of variables for debugging without rendering the template.
For example:
class IndexController(BaseController):
def index(self):
# Return a rendered template
#return render('/index.mako')
# or, return a response
return render('/index.mako' )
def test(self):
v = request.params
return v
I would like to view the contents of array v, but I can't figure out how to do it !!
Thanks.
|
[
"You can use cgitb to debug web applications, it can output detailed tracebacks to files, including variables contents. Here is an article detailing how to use it.\nIf you can see the server stdout you can also simply print the variable, or else write it to a file: open(\"my-debug-log.txt\", \"w\").write(repr(variable)). pprint can help making complex data structures (nested arrays, complex dicts, etc...) easier to read in this case.\n"
] |
[
1
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0002188496_pylons_python.txt
|
Q:
Getting invalid image error in Django, but PIL is installed and passes all tests
So I've finally successfully installed PIL (after many difficulties) on RHEL5 with Django (development version) and Python 2.6 installed at /opt/python2.6.
Running selftest.py shows that everything appears to be installed correctly:
$ python2.6 selftest.py
57 tests passed.
I can upload .png files and .gif files without difficulties, but run into problems when trying to upload .jpg files using the ImageField: "Upload a valid image. The file you uploaded was either not an image or a corrupted image."
I saw this other question and ran the test to see if PIL would verify the image, and it did:
>>> from PIL import Image
>>> trial_image=Image.open("/tmp/jordanthecoder.jpg")
>>> trial_image.verify()
>>>
What could be going on? Obviously, allowing JPEG is kind of important. I realize one option is to use a FileField instead and then check to make sure it is one of GIF, PNG, or JPEG, but I'd much rather use the built-in object.
In case this is helpful, here is the verbose display for the shell above:
$ python2.6 -v
Python 2.6.4 (r264:75706, Jan 15 2010, 14:42:33)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/readline.so", 2);
import readline # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/readline.so
>>> from PIL import Image
import PIL # directory /opt/python2.6/lib/python2.6/site-packages/PIL
# /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.py
import PIL # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/Image.py
import PIL.Image # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc
# /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc matches /opt/python2.6/lib/python2.6/lib-tk/FixTk.py
import FixTk # precompiled from /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc
import ctypes # directory /opt/python2.6/lib/python2.6/ctypes
# /opt/python2.6/lib/python2.6/ctypes/__init__.pyc matches /opt/python2.6/lib/python2.6/ctypes/__init__.py
import ctypes # precompiled from /opt/python2.6/lib/python2.6/ctypes/__init__.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so", 2);
import _ctypes # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so
# /opt/python2.6/lib/python2.6/struct.pyc matches /opt/python2.6/lib/python2.6/struct.py
import struct # precompiled from /opt/python2.6/lib/python2.6/struct.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_struct.so", 2);
import _struct # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_struct.so
# /opt/python2.6/lib/python2.6/ctypes/_endian.pyc matches /opt/python2.6/lib/python2.6/ctypes/_endian.py
import ctypes._endian # precompiled from /opt/python2.6/lib/python2.6/ctypes/_endian.pyc
dlopen("/opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so", 2);
import PIL._imaging # dynamically loaded from /opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.py
import PIL.ImageMode # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.py
import PIL.ImagePalette # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/array.so", 2);
import array # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/array.so
# /opt/python2.6/lib/python2.6/string.pyc matches /opt/python2.6/lib/python2.6/string.py
import string # precompiled from /opt/python2.6/lib/python2.6/string.pyc
# /opt/python2.6/lib/python2.6/re.pyc matches /opt/python2.6/lib/python2.6/re.py
import re # precompiled from /opt/python2.6/lib/python2.6/re.pyc
# /opt/python2.6/lib/python2.6/sre_compile.pyc matches /opt/python2.6/lib/python2.6/sre_compile.py
import sre_compile # precompiled from /opt/python2.6/lib/python2.6/sre_compile.pyc
import _sre # builtin
# /opt/python2.6/lib/python2.6/sre_parse.pyc matches /opt/python2.6/lib/python2.6/sre_parse.py
import sre_parse # precompiled from /opt/python2.6/lib/python2.6/sre_parse.pyc
# /opt/python2.6/lib/python2.6/sre_constants.pyc matches /opt/python2.6/lib/python2.6/sre_constants.py
import sre_constants # precompiled from /opt/python2.6/lib/python2.6/sre_constants.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/strop.so", 2);
import strop # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/strop.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/operator.so", 2);
import operator # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/operator.so
>>> trial_image=Image.open("/tmp/jordanthecoder.jpg")
# /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.py
import PIL.BmpImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.py
import PIL.ImageFile # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc
# /opt/python2.6/lib/python2.6/traceback.pyc matches /opt/python2.6/lib/python2.6/traceback.py
import traceback # precompiled from /opt/python2.6/lib/python2.6/traceback.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.py
import PIL.GifImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.py
import PIL.JpegImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.py
import PIL.PpmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.py
import PIL.PngImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc
>>> trial_image.verify()
>>> fake_image = Image.open("/tmp/fakeimage.jpg") #text file ending in .jpg
# /opt/python2.6/lib/python2.6/site-packages/PIL/CurImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/CurImagePlugin.py
import PIL.CurImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/CurImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ArgImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ArgImagePlugin.py
import PIL.ArgImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ArgImagePlugin.pyc
import marshal # builtin
# /opt/python2.6/lib/python2.6/site-packages/PIL/Hdf5StubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/Hdf5StubImagePlugin.py
import PIL.Hdf5StubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/Hdf5StubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/MspImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/MspImagePlugin.py
import PIL.MspImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/MspImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/MicImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/MicImagePlugin.py
import PIL.MicImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/MicImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/TiffImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/TiffImagePlugin.py
import PIL.TiffImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/TiffImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/OleFileIO.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/OleFileIO.py
import PIL.OleFileIO # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/OleFileIO.pyc
# /opt/python2.6/lib/python2.6/StringIO.pyc matches /opt/python2.6/lib/python2.6/StringIO.py
import StringIO # precompiled from /opt/python2.6/lib/python2.6/StringIO.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/FitsStubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/FitsStubImagePlugin.py
import PIL.FitsStubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/FitsStubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/MpegImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/MpegImagePlugin.py
import PIL.MpegImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/MpegImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PixarImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PixarImagePlugin.py
import PIL.PixarImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PixarImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/DcxImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/DcxImagePlugin.py
import PIL.DcxImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/DcxImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PcxImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PcxImagePlugin.py
import PIL.PcxImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PcxImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/WmfImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/WmfImagePlugin.py
import PIL.WmfImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/WmfImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/XVThumbImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/XVThumbImagePlugin.py
import PIL.XVThumbImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/XVThumbImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/XbmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/XbmImagePlugin.py
import PIL.XbmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/XbmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImtImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImtImagePlugin.py
import PIL.ImtImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImtImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/IptcImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/IptcImagePlugin.py
import PIL.IptcImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/IptcImagePlugin.pyc
# /opt/python2.6/lib/python2.6/tempfile.pyc matches /opt/python2.6/lib/python2.6/tempfile.py
import tempfile # precompiled from /opt/python2.6/lib/python2.6/tempfile.pyc
# /opt/python2.6/lib/python2.6/random.pyc matches /opt/python2.6/lib/python2.6/random.py
import random # precompiled from /opt/python2.6/lib/python2.6/random.pyc
# /opt/python2.6/lib/python2.6/__future__.pyc matches /opt/python2.6/lib/python2.6/__future__.py
import __future__ # precompiled from /opt/python2.6/lib/python2.6/__future__.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/math.so", 2);
import math # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/math.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/binascii.so", 2);
import binascii # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/binascii.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_random.so", 2);
import _random # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_random.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/cStringIO.so", 2);
import cStringIO # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/cStringIO.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/fcntl.so", 2);
import fcntl # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/fcntl.so
import thread # builtin
# /opt/python2.6/lib/python2.6/site-packages/PIL/GribStubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GribStubImagePlugin.py
import PIL.GribStubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GribStubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/TgaImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/TgaImagePlugin.py
import PIL.TgaImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/TgaImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/BufrStubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/BufrStubImagePlugin.py
import PIL.BufrStubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/BufrStubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/FpxImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/FpxImagePlugin.py
import PIL.FpxImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/FpxImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/SgiImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/SgiImagePlugin.py
import PIL.SgiImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/SgiImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/FliImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/FliImagePlugin.py
import PIL.FliImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/FliImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PcdImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PcdImagePlugin.py
import PIL.PcdImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PcdImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PalmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PalmImagePlugin.py
import PIL.PalmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PalmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/XpmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/XpmImagePlugin.py
import PIL.XpmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/XpmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImImagePlugin.py
import PIL.ImImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/SunImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/SunImagePlugin.py
import PIL.SunImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/SunImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/IcnsImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/IcnsImagePlugin.py
import PIL.IcnsImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/IcnsImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/McIdasImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/McIdasImagePlugin.py
import PIL.McIdasImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/McIdasImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PdfImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PdfImagePlugin.py
import PIL.PdfImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PdfImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/GbrImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GbrImagePlugin.py
import PIL.GbrImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GbrImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/EpsImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/EpsImagePlugin.py
import PIL.EpsImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/EpsImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/IcoImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/IcoImagePlugin.py
import PIL.IcoImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/IcoImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/SpiderImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/SpiderImagePlugin.py
import PIL.SpiderImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/SpiderImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PsdImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PsdImagePlugin.py
import PIL.PsdImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PsdImagePlugin.pyc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/python2.6/lib/python2.6/site-packages/PIL/Image.py", line 1916, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file
UPDATE
Here is the output for $ python manage.py shell (skipping initial import statements):
Python 2.6.4 (r264:75706, Jan 15 2010, 14:42:33)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from PIL import Image
import PIL # directory /opt/python2.6/lib/python2.6/site-packages/PIL
# /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.py
import PIL # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/Image.py
import PIL.Image # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc
# /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc matches /opt/python2.6/lib/python2.6/lib-tk/FixTk.py
import FixTk # precompiled from /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc
import ctypes # directory /opt/python2.6/lib/python2.6/ctypes
# /opt/python2.6/lib/python2.6/ctypes/__init__.pyc matches /opt/python2.6/lib/python2.6/ctypes/__init__.py
import ctypes # precompiled from /opt/python2.6/lib/python2.6/ctypes/__init__.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so", 2);
import _ctypes # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so
# /opt/python2.6/lib/python2.6/ctypes/_endian.pyc matches /opt/python2.6/lib/python2.6/ctypes/_endian.py
import ctypes._endian # precompiled from /opt/python2.6/lib/python2.6/ctypes/_endian.pyc
dlopen("/opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so", 2);
import PIL._imaging # dynamically loaded from /opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.py
import PIL.ImageMode # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.py
import PIL.ImagePalette # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc
>>> trial_image=Image.open("/tmp/jordanthecoder.jpg")
# /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.py
import PIL.BmpImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.py
import PIL.ImageFile # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.py
import PIL.GifImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.py
import PIL.JpegImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.py
import PIL.PpmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.py
import PIL.PngImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc
>>> trial_image.verify()
>>>
UPDATE #2:
Okay, so I decided to bypass ImageField altogether and just see what PIL does on its own. This is the code in question (in my views.py file):
def test_image(request):
i = Image.open("/tmp/jordanthecoder.jpg")
t = i.verify()
return HttpResponse("Image is "+repr(i.info))
This is the webpage output:
Image is {'jfif_version': (1, 1), 'jfif': 257, 'jfif_unit': 1, 'jfif_density': (72, 72), 'dpi': (72, 72)}
UPDATE #3
So, these are the modules and paths for the two different systems. I'm not exactly sure why they're so different and what I can do to change the behavior of the web version.
They actually were using different JSON modules, pretty sure that that makes no difference. Other than that, here are the different modules. Assume these modules are all somewhere in /opt/python2.6/...
Only in the web version:
django.contrib.sessions.*, django.core.email, django.core.handlers.*, django.core.mail, django.core.mimetypes, django.core.os, django.core.random, django.core.smtplib, django.core.socket, django.core.time, django.middleware.*, email.*, encodings.ascii, hmac, mimetypes, mod_wsgi, smtplib, uu
Only in the shell version:
code, codeop, django.core.management.*, readline, rlcompleter, settings, user
Thanks
** UPDATE #4 **
Looks like the problem is that apache is using the incorrect libjpeg.so, whereas python is using the right one. I've created a more generalized version of the question that isn't specific to Django.
A:
See possible answer in:
Is it possible to control which libraries apache uses?
Referencing here so can still get bounty if awarded. :-)
A:
My impression of the PIL JPEG problem is that it's almost always a system configuration problem.
You built and configured PIL and tested with that version and it worked. So, my guess is that Django is pulling in a different PIL, probably one built without JPEG support or that can't find libjpeg.
You can confirm this by running your test again but using python -v manage.py shell instead of running python2.6 directly. You need to be careful here though and make sure your python executable and PYTHONPATH exactly match what is loaded by your web server.
|
Getting invalid image error in Django, but PIL is installed and passes all tests
|
So I've finally successfully installed PIL (after many difficulties) on RHEL5 with Django (development version) and Python 2.6 installed at /opt/python2.6.
Running selftest.py shows that everything appears to be installed correctly:
$ python2.6 selftest.py
57 tests passed.
I can upload .png files and .gif files without difficulties, but run into problems when trying to upload .jpg files using the ImageField: "Upload a valid image. The file you uploaded was either not an image or a corrupted image."
I saw this other question and ran the test to see if PIL would verify the image, and it did:
>>> from PIL import Image
>>> trial_image=Image.open("/tmp/jordanthecoder.jpg")
>>> trial_image.verify()
>>>
What could be going on? Obviously, allowing JPEG is kind of important. I realize one option is to use a FileField instead and then check to make sure it is one of GIF, PNG, or JPEG, but I'd much rather use the built-in object.
In case this is helpful, here is the verbose display for the shell above:
$ python2.6 -v
Python 2.6.4 (r264:75706, Jan 15 2010, 14:42:33)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/readline.so", 2);
import readline # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/readline.so
>>> from PIL import Image
import PIL # directory /opt/python2.6/lib/python2.6/site-packages/PIL
# /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.py
import PIL # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/Image.py
import PIL.Image # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc
# /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc matches /opt/python2.6/lib/python2.6/lib-tk/FixTk.py
import FixTk # precompiled from /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc
import ctypes # directory /opt/python2.6/lib/python2.6/ctypes
# /opt/python2.6/lib/python2.6/ctypes/__init__.pyc matches /opt/python2.6/lib/python2.6/ctypes/__init__.py
import ctypes # precompiled from /opt/python2.6/lib/python2.6/ctypes/__init__.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so", 2);
import _ctypes # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so
# /opt/python2.6/lib/python2.6/struct.pyc matches /opt/python2.6/lib/python2.6/struct.py
import struct # precompiled from /opt/python2.6/lib/python2.6/struct.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_struct.so", 2);
import _struct # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_struct.so
# /opt/python2.6/lib/python2.6/ctypes/_endian.pyc matches /opt/python2.6/lib/python2.6/ctypes/_endian.py
import ctypes._endian # precompiled from /opt/python2.6/lib/python2.6/ctypes/_endian.pyc
dlopen("/opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so", 2);
import PIL._imaging # dynamically loaded from /opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.py
import PIL.ImageMode # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.py
import PIL.ImagePalette # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/array.so", 2);
import array # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/array.so
# /opt/python2.6/lib/python2.6/string.pyc matches /opt/python2.6/lib/python2.6/string.py
import string # precompiled from /opt/python2.6/lib/python2.6/string.pyc
# /opt/python2.6/lib/python2.6/re.pyc matches /opt/python2.6/lib/python2.6/re.py
import re # precompiled from /opt/python2.6/lib/python2.6/re.pyc
# /opt/python2.6/lib/python2.6/sre_compile.pyc matches /opt/python2.6/lib/python2.6/sre_compile.py
import sre_compile # precompiled from /opt/python2.6/lib/python2.6/sre_compile.pyc
import _sre # builtin
# /opt/python2.6/lib/python2.6/sre_parse.pyc matches /opt/python2.6/lib/python2.6/sre_parse.py
import sre_parse # precompiled from /opt/python2.6/lib/python2.6/sre_parse.pyc
# /opt/python2.6/lib/python2.6/sre_constants.pyc matches /opt/python2.6/lib/python2.6/sre_constants.py
import sre_constants # precompiled from /opt/python2.6/lib/python2.6/sre_constants.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/strop.so", 2);
import strop # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/strop.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/operator.so", 2);
import operator # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/operator.so
>>> trial_image=Image.open("/tmp/jordanthecoder.jpg")
# /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.py
import PIL.BmpImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.py
import PIL.ImageFile # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc
# /opt/python2.6/lib/python2.6/traceback.pyc matches /opt/python2.6/lib/python2.6/traceback.py
import traceback # precompiled from /opt/python2.6/lib/python2.6/traceback.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.py
import PIL.GifImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.py
import PIL.JpegImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.py
import PIL.PpmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.py
import PIL.PngImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc
>>> trial_image.verify()
>>> fake_image = Image.open("/tmp/fakeimage.jpg") #text file ending in .jpg
# /opt/python2.6/lib/python2.6/site-packages/PIL/CurImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/CurImagePlugin.py
import PIL.CurImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/CurImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ArgImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ArgImagePlugin.py
import PIL.ArgImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ArgImagePlugin.pyc
import marshal # builtin
# /opt/python2.6/lib/python2.6/site-packages/PIL/Hdf5StubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/Hdf5StubImagePlugin.py
import PIL.Hdf5StubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/Hdf5StubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/MspImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/MspImagePlugin.py
import PIL.MspImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/MspImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/MicImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/MicImagePlugin.py
import PIL.MicImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/MicImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/TiffImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/TiffImagePlugin.py
import PIL.TiffImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/TiffImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/OleFileIO.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/OleFileIO.py
import PIL.OleFileIO # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/OleFileIO.pyc
# /opt/python2.6/lib/python2.6/StringIO.pyc matches /opt/python2.6/lib/python2.6/StringIO.py
import StringIO # precompiled from /opt/python2.6/lib/python2.6/StringIO.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/FitsStubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/FitsStubImagePlugin.py
import PIL.FitsStubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/FitsStubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/MpegImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/MpegImagePlugin.py
import PIL.MpegImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/MpegImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PixarImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PixarImagePlugin.py
import PIL.PixarImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PixarImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/DcxImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/DcxImagePlugin.py
import PIL.DcxImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/DcxImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PcxImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PcxImagePlugin.py
import PIL.PcxImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PcxImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/WmfImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/WmfImagePlugin.py
import PIL.WmfImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/WmfImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/XVThumbImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/XVThumbImagePlugin.py
import PIL.XVThumbImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/XVThumbImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/XbmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/XbmImagePlugin.py
import PIL.XbmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/XbmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImtImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImtImagePlugin.py
import PIL.ImtImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImtImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/IptcImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/IptcImagePlugin.py
import PIL.IptcImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/IptcImagePlugin.pyc
# /opt/python2.6/lib/python2.6/tempfile.pyc matches /opt/python2.6/lib/python2.6/tempfile.py
import tempfile # precompiled from /opt/python2.6/lib/python2.6/tempfile.pyc
# /opt/python2.6/lib/python2.6/random.pyc matches /opt/python2.6/lib/python2.6/random.py
import random # precompiled from /opt/python2.6/lib/python2.6/random.pyc
# /opt/python2.6/lib/python2.6/__future__.pyc matches /opt/python2.6/lib/python2.6/__future__.py
import __future__ # precompiled from /opt/python2.6/lib/python2.6/__future__.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/math.so", 2);
import math # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/math.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/binascii.so", 2);
import binascii # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/binascii.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_random.so", 2);
import _random # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_random.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/cStringIO.so", 2);
import cStringIO # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/cStringIO.so
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/fcntl.so", 2);
import fcntl # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/fcntl.so
import thread # builtin
# /opt/python2.6/lib/python2.6/site-packages/PIL/GribStubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GribStubImagePlugin.py
import PIL.GribStubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GribStubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/TgaImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/TgaImagePlugin.py
import PIL.TgaImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/TgaImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/BufrStubImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/BufrStubImagePlugin.py
import PIL.BufrStubImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/BufrStubImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/FpxImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/FpxImagePlugin.py
import PIL.FpxImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/FpxImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/SgiImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/SgiImagePlugin.py
import PIL.SgiImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/SgiImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/FliImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/FliImagePlugin.py
import PIL.FliImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/FliImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PcdImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PcdImagePlugin.py
import PIL.PcdImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PcdImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PalmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PalmImagePlugin.py
import PIL.PalmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PalmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/XpmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/XpmImagePlugin.py
import PIL.XpmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/XpmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImImagePlugin.py
import PIL.ImImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/SunImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/SunImagePlugin.py
import PIL.SunImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/SunImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/IcnsImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/IcnsImagePlugin.py
import PIL.IcnsImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/IcnsImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/McIdasImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/McIdasImagePlugin.py
import PIL.McIdasImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/McIdasImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PdfImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PdfImagePlugin.py
import PIL.PdfImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PdfImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/GbrImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GbrImagePlugin.py
import PIL.GbrImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GbrImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/EpsImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/EpsImagePlugin.py
import PIL.EpsImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/EpsImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/IcoImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/IcoImagePlugin.py
import PIL.IcoImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/IcoImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/SpiderImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/SpiderImagePlugin.py
import PIL.SpiderImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/SpiderImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PsdImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PsdImagePlugin.py
import PIL.PsdImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PsdImagePlugin.pyc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/python2.6/lib/python2.6/site-packages/PIL/Image.py", line 1916, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file
UPDATE
Here is the output for $ python manage.py shell (skipping initial import statements):
Python 2.6.4 (r264:75706, Jan 15 2010, 14:42:33)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from PIL import Image
import PIL # directory /opt/python2.6/lib/python2.6/site-packages/PIL
# /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.py
import PIL # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/__init__.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/Image.py
import PIL.Image # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/Image.pyc
# /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc matches /opt/python2.6/lib/python2.6/lib-tk/FixTk.py
import FixTk # precompiled from /opt/python2.6/lib/python2.6/lib-tk/FixTk.pyc
import ctypes # directory /opt/python2.6/lib/python2.6/ctypes
# /opt/python2.6/lib/python2.6/ctypes/__init__.pyc matches /opt/python2.6/lib/python2.6/ctypes/__init__.py
import ctypes # precompiled from /opt/python2.6/lib/python2.6/ctypes/__init__.pyc
dlopen("/opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so", 2);
import _ctypes # dynamically loaded from /opt/python2.6/lib/python2.6/lib-dynload/_ctypes.so
# /opt/python2.6/lib/python2.6/ctypes/_endian.pyc matches /opt/python2.6/lib/python2.6/ctypes/_endian.py
import ctypes._endian # precompiled from /opt/python2.6/lib/python2.6/ctypes/_endian.pyc
dlopen("/opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so", 2);
import PIL._imaging # dynamically loaded from /opt/python2.6/lib/python2.6/site-packages/PIL/_imaging.so
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.py
import PIL.ImageMode # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageMode.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.py
import PIL.ImagePalette # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImagePalette.pyc
>>> trial_image=Image.open("/tmp/jordanthecoder.jpg")
# /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.py
import PIL.BmpImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/BmpImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.py
import PIL.ImageFile # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/ImageFile.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.py
import PIL.GifImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/GifImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.py
import PIL.JpegImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.py
import PIL.PpmImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PpmImagePlugin.pyc
# /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc matches /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.py
import PIL.PngImagePlugin # precompiled from /opt/python2.6/lib/python2.6/site-packages/PIL/PngImagePlugin.pyc
>>> trial_image.verify()
>>>
UPDATE #2:
Okay, so I decided to bypass ImageField altogether and just see what PIL does on its own. This is the code in question (in my views.py file):
def test_image(request):
i = Image.open("/tmp/jordanthecoder.jpg")
t = i.verify()
return HttpResponse("Image is "+repr(i.info))
This is the webpage output:
Image is {'jfif_version': (1, 1), 'jfif': 257, 'jfif_unit': 1, 'jfif_density': (72, 72), 'dpi': (72, 72)}
UPDATE #3
So, these are the modules and paths for the two different systems. I'm not exactly sure why they're so different and what I can do to change the behavior of the web version.
They actually were using different JSON modules, pretty sure that that makes no difference. Other than that, here are the different modules. Assume these modules are all somewhere in /opt/python2.6/...
Only in the web version:
django.contrib.sessions.*, django.core.email, django.core.handlers.*, django.core.mail, django.core.mimetypes, django.core.os, django.core.random, django.core.smtplib, django.core.socket, django.core.time, django.middleware.*, email.*, encodings.ascii, hmac, mimetypes, mod_wsgi, smtplib, uu
Only in the shell version:
code, codeop, django.core.management.*, readline, rlcompleter, settings, user
Thanks
** UPDATE #4 **
Looks like the problem is that apache is using the incorrect libjpeg.so, whereas python is using the right one. I've created a more generalized version of the question that isn't specific to Django.
|
[
"See possible answer in:\nIs it possible to control which libraries apache uses?\nReferencing here so can still get bounty if awarded. :-)\n",
"My impression of the PIL JPEG problem is that it's almost always a system configuration problem.\nYou built and configured PIL and tested with that version and it worked. So, my guess is that Django is pulling in a different PIL, probably one built without JPEG support or that can't find libjpeg.\nYou can confirm this by running your test again but using python -v manage.py shell instead of running python2.6 directly. You need to be careful here though and make sure your python executable and PYTHONPATH exactly match what is loaded by your web server.\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"django_models",
"python",
"python_imaging_library"
] |
stackoverflow_0002110588_django_django_models_python_python_imaging_library.txt
|
Q:
Integrating Python or Perl with PHP
I'm going to help my friend in a improve of his phpBB board, but I want to make somethings there in Python or Perl. But it's possible to integrate these languages with PHP?
A:
You can always call the python or perl interpreter from within PHP! Minimalistic interchange is possible by means of passing command line arguments and capturing stdout (exec or passthru are related php functions).
However, I don't think its's a good idea - using two interpreters instead of one doubles the overall runtime overhead and startup time.
A:
I'd say that the only reasonable way of doing that is if you are making a separate service, that you talk to via Ajax or XML or something like that. Everything else is more trouble than it's worth.
A:
There is Perl PECL package to integrate Perl into PHP.
|
Integrating Python or Perl with PHP
|
I'm going to help my friend in a improve of his phpBB board, but I want to make somethings there in Python or Perl. But it's possible to integrate these languages with PHP?
|
[
"You can always call the python or perl interpreter from within PHP! Minimalistic interchange is possible by means of passing command line arguments and capturing stdout (exec or passthru are related php functions).\nHowever, I don't think its's a good idea - using two interpreters instead of one doubles the overall runtime overhead and startup time.\n",
"I'd say that the only reasonable way of doing that is if you are making a separate service, that you talk to via Ajax or XML or something like that. Everything else is more trouble than it's worth.\n",
"There is Perl PECL package to integrate Perl into PHP.\n"
] |
[
8,
8,
3
] |
[] |
[] |
[
"integration",
"perl",
"php",
"phpbb",
"python"
] |
stackoverflow_0002187998_integration_perl_php_phpbb_python.txt
|
Q:
unicode class in Python
help(unicode) prints something like:
class unicode(basestring)
| unicode(string [, encoding[, errors]]) -> object
...
but you can use something different from a basestring as argument, you can do unicode(1) and get u'1'. What happens in that call? int don't have a __unicode__ method to be called.
A:
Same as unicode(str(1)).
>>> class thing(object):
... def __str__(self):
... print "__str__ called on " + repr(self)
... return repr(self)
...
>>> a = thing()
>>> a
<__main__.thing object at 0x7f2f972795d0>
>>> unicode(a)
__str__ called on <__main__.thing object at 0x7f2f972795d0>
u'<__main__.thing object at 0x7f2f972795d0>'
If you really want to see the gritty bits underneath, open up the Python interpreter source code.
Objects/unicodeobject.c#PyUnicode_Type defines the unicode type, with constructor .tp_new=unicode_new.
Since the optional arguments encoding or errors are not given, and a unicode object is being constructed (as opposed to a unicode subclass), Objects/unicodeobject.c#unicode_new calls PyObject_Unicode.
Objects/object.c#PyObject_Unicode calls the __unicode__ method if it exists. If not, it falls back to PY_Type(v)->tp_str (a.k.a. __str__) or PY_Type(v)->tp_repr (a.k.a. __repr__). It then passes the result to PyUnicode_FromEncodedObject.
Objects/unicodeobject.c#PyUnicode_FromEncodedObject finds that it was given a string, and passes it on to PyUnicode_Decode, which returns a unicode object.
Finally, PyObject_Unicode returns to unicode_new, which returns this unicode object.
In short, unicode() will automatically stringify your object if it needs to. This is Python working as expected.
A:
If __unicode__ exists it is called, otherwise it falls back to __str__
class A(int):
def __str__(self):
print "A.str"
return int.__str__(self)
def __unicode__(self):
print "A.unicode"
return int.__str__(self)
class B(int):
def __str__(self):
print "B.str"
return int.__str__(self)
unicode(A(1)) # prints "A.unicode"
unicode(B(1)) # prints "B.str"
A:
If there is no __unicode__ method, the __str__ method will be called instead. Regardless of which of these methods is called, if a unicode is returned, it will be passed on as-is. If a str is returned, it will be decoded using the default encoding, as returned by sys.getdefaultencoding(), which should almost always be 'ascii'. If some other kind of object is returned, a TypeError will be raised.
(It is possible, by reloading the sys module, to change the default encoding by calling sys.setdefaultencoding(); this is basically always a bad idea.)
|
unicode class in Python
|
help(unicode) prints something like:
class unicode(basestring)
| unicode(string [, encoding[, errors]]) -> object
...
but you can use something different from a basestring as argument, you can do unicode(1) and get u'1'. What happens in that call? int don't have a __unicode__ method to be called.
|
[
"Same as unicode(str(1)).\n\n>>> class thing(object):\n... def __str__(self):\n... print \"__str__ called on \" + repr(self)\n... return repr(self)\n...\n>>> a = thing()\n>>> a\n<__main__.thing object at 0x7f2f972795d0>\n>>> unicode(a)\n__str__ called on <__main__.thing object at 0x7f2f972795d0>\nu'<__main__.thing object at 0x7f2f972795d0>'\n\n\nIf you really want to see the gritty bits underneath, open up the Python interpreter source code.\nObjects/unicodeobject.c#PyUnicode_Type defines the unicode type, with constructor .tp_new=unicode_new.\nSince the optional arguments encoding or errors are not given, and a unicode object is being constructed (as opposed to a unicode subclass), Objects/unicodeobject.c#unicode_new calls PyObject_Unicode.\nObjects/object.c#PyObject_Unicode calls the __unicode__ method if it exists. If not, it falls back to PY_Type(v)->tp_str (a.k.a. __str__) or PY_Type(v)->tp_repr (a.k.a. __repr__). It then passes the result to PyUnicode_FromEncodedObject.\nObjects/unicodeobject.c#PyUnicode_FromEncodedObject finds that it was given a string, and passes it on to PyUnicode_Decode, which returns a unicode object.\nFinally, PyObject_Unicode returns to unicode_new, which returns this unicode object.\nIn short, unicode() will automatically stringify your object if it needs to. This is Python working as expected.\n",
"If __unicode__ exists it is called, otherwise it falls back to __str__ \nclass A(int):\n def __str__(self):\n print \"A.str\"\n return int.__str__(self)\n\n def __unicode__(self):\n print \"A.unicode\"\n return int.__str__(self)\n\nclass B(int):\n def __str__(self):\n print \"B.str\"\n return int.__str__(self)\n\n\nunicode(A(1)) # prints \"A.unicode\"\nunicode(B(1)) # prints \"B.str\"\n\n",
"If there is no __unicode__ method, the __str__ method will be called instead. Regardless of which of these methods is called, if a unicode is returned, it will be passed on as-is. If a str is returned, it will be decoded using the default encoding, as returned by sys.getdefaultencoding(), which should almost always be 'ascii'. If some other kind of object is returned, a TypeError will be raised.\n(It is possible, by reloading the sys module, to change the default encoding by calling sys.setdefaultencoding(); this is basically always a bad idea.)\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0002189156_python_unicode.txt
|
Q:
What is the elegant way to get the arguments to a playAudio call from this list
I know this is the basic.
I'm just wondering what is the elegant way to do it.
For example:
I want the the 'python01.wav' and 'py*thon' strings from this list
The list is like this:
[
[('name', 'entry')],
[('class', 'entry')],
[('type', 'text/javascript'), ('src', '/term_added.php?hw=python')],
[('type', 'text/javascript')],
[('class', 'headword')],
[('class', 'hw')],
[],
[('class', 'pr')],
[('class', 'unicode')],
[('class', 'unicode')],
[('class', 'unicode')],
[('class', 'unicode')],
[],
[('href', '#'), ('onclick', "playAudio('python01.wav', 'py*thon'); return false;"), ('class', 'audio_link'), ('target', '_blank')],
[('src', '/images/audio.gif'), ('alt', 'Listen to audio'), ('title', 'Listen to audio')],
[],
[('class', 'fl')],
[],
[('class', 'in')],
[('class', 'il')],
[('class', 'if')],
[],
[('class', 'def')],
[('class', 'gram')],
[],
]
Thank you for your help!
A:
Perhaps not the greatest solution, but appears to do what you want:
l = [huge list from your example]
for e in l: # for each list
for t in e: # for each tuple
for s in t: # each string
if 'playAudio' in s:
args = s[9:].split(',') #skip 'playAudio' split on comma
print "%s,%s" % (args[0].strip('('),
args[1].lstrip(" ")[0:args[1].find(')')]
I leave 'optimizing' this an exercise to you. If you could explain where this data is coming from and what sort of characteristics it has (can playAudio only be attached to things with an HREF attribute?), we could give you a better solution.
EDIT:
Personally for your specific example, I would do this:
from BeautifulSoup import BeautifulSoup, SoupStrainer
import re
import urllib2
doc = urllib2.urlopen("http://www.learnersdictionary.com/search/python").read()
doc = doc.replace('</SCR', '')
audioLinks = SoupStrainer('a', onclick=re.compile(r'^playAudio'))
soup = [str(elm) for elm in BeautifulSoup(doc, parseOnlyThese=audio)]
for elm in soup:
print re.search(r'playAudio\((.*[^)])\)', elm).group(1)
# prints 'python01.wav', 'py*thon'
A:
return ('python01.wav', 'py*thon')
This satisfies your specification perfectly.
But if I had to guess, I don't think it's what you want.
So why don't you give us enough information that we can actually figure out what strings you want to get? Is it everything between single-quotes in one of the strings? Everything between single-quotes that contains the letters p,y,t,h,o,n in that order? The arguments to a playAudio call?
Without knowing what you want, we can't give you a solution that solves your problem.
|
What is the elegant way to get the arguments to a playAudio call from this list
|
I know this is the basic.
I'm just wondering what is the elegant way to do it.
For example:
I want the the 'python01.wav' and 'py*thon' strings from this list
The list is like this:
[
[('name', 'entry')],
[('class', 'entry')],
[('type', 'text/javascript'), ('src', '/term_added.php?hw=python')],
[('type', 'text/javascript')],
[('class', 'headword')],
[('class', 'hw')],
[],
[('class', 'pr')],
[('class', 'unicode')],
[('class', 'unicode')],
[('class', 'unicode')],
[('class', 'unicode')],
[],
[('href', '#'), ('onclick', "playAudio('python01.wav', 'py*thon'); return false;"), ('class', 'audio_link'), ('target', '_blank')],
[('src', '/images/audio.gif'), ('alt', 'Listen to audio'), ('title', 'Listen to audio')],
[],
[('class', 'fl')],
[],
[('class', 'in')],
[('class', 'il')],
[('class', 'if')],
[],
[('class', 'def')],
[('class', 'gram')],
[],
]
Thank you for your help!
|
[
"Perhaps not the greatest solution, but appears to do what you want:\nl = [huge list from your example]\nfor e in l: # for each list\n for t in e: # for each tuple\n for s in t: # each string\n if 'playAudio' in s:\n args = s[9:].split(',') #skip 'playAudio' split on comma\n print \"%s,%s\" % (args[0].strip('('),\n args[1].lstrip(\" \")[0:args[1].find(')')]\n\nI leave 'optimizing' this an exercise to you. If you could explain where this data is coming from and what sort of characteristics it has (can playAudio only be attached to things with an HREF attribute?), we could give you a better solution.\nEDIT:\nPersonally for your specific example, I would do this:\nfrom BeautifulSoup import BeautifulSoup, SoupStrainer\nimport re\nimport urllib2\n\ndoc = urllib2.urlopen(\"http://www.learnersdictionary.com/search/python\").read()\ndoc = doc.replace('</SCR', '')\naudioLinks = SoupStrainer('a', onclick=re.compile(r'^playAudio'))\nsoup = [str(elm) for elm in BeautifulSoup(doc, parseOnlyThese=audio)]\nfor elm in soup:\n print re.search(r'playAudio\\((.*[^)])\\)', elm).group(1)\n # prints 'python01.wav', 'py*thon'\n\n",
"return ('python01.wav', 'py*thon')\n\nThis satisfies your specification perfectly.\nBut if I had to guess, I don't think it's what you want.\nSo why don't you give us enough information that we can actually figure out what strings you want to get? Is it everything between single-quotes in one of the strings? Everything between single-quotes that contains the letters p,y,t,h,o,n in that order? The arguments to a playAudio call?\nWithout knowing what you want, we can't give you a solution that solves your problem.\n"
] |
[
2,
1
] |
[] |
[] |
[
"list",
"python",
"string"
] |
stackoverflow_0002189259_list_python_string.txt
|
Q:
performance issue when import reactor module before os.fork()
i got a performance issue when trying to do:
from twisted.internet import reactor
#some codes here
pid = os.fork()
if not pid:
#some codes blahblahblah
reactor.run()
this caused very low performance and i didn't find useful informations from the official documentation, i believe it because i import reactor module before os.fork(), any idea?
A:
Can't you use subprocess instead of os.fork?
|
performance issue when import reactor module before os.fork()
|
i got a performance issue when trying to do:
from twisted.internet import reactor
#some codes here
pid = os.fork()
if not pid:
#some codes blahblahblah
reactor.run()
this caused very low performance and i didn't find useful informations from the official documentation, i believe it because i import reactor module before os.fork(), any idea?
|
[
"Can't you use subprocess instead of os.fork?\n"
] |
[
0
] |
[] |
[] |
[
"performance",
"python",
"twisted"
] |
stackoverflow_0002189332_performance_python_twisted.txt
|
Q:
Django ORM's "related data" loading behavior
In LINQ (I come from a C# background), you can manually load data for related tables via the Include("xxx") method
from a in ctx.MainTable.Include("SubTable")
select a;
In the above code, every instance of MainTable is loaded and all the data for MainTable.SubTable is also loaded. If "Include" is not called, every returned MainTable's SubTable property will return null.
Are there equivalent methods for the Django ORM? If not, what's the default Django behavior for situtions like the above?
A:
See this:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4
You create a select_related query set to follow relationships and pre-fetch related rows.
Normally, you don't waste much time doing this until you know that the individual fetches done automagically by the ORM are too slow.
When you simply name a related object field:
x = MainTable.objects.get( id="some Object" )
y= x.subTable
The ORM will do the of the related subTable row. lazily.
You can't easily fetch an entire table into memory. QuerySets are "lazy" and don't fetch rows until there's no possible excuse. Consider this.
for m in MainTable.objects.all():
y = m.subTable
if y.someAttribute > 5:
break
Then you may not actually need all the objects in MainTable. The query set is ready to fetch them. It just doesn't actually fetch them all. That's why we don't generally do anything more than x.subTable and leave it to the ORM to fetch the row as needed.
Once in a while you can prove that it's too slow. Then you can do MainTable.objects.select_related()... and force navigation to rows in other tables.
|
Django ORM's "related data" loading behavior
|
In LINQ (I come from a C# background), you can manually load data for related tables via the Include("xxx") method
from a in ctx.MainTable.Include("SubTable")
select a;
In the above code, every instance of MainTable is loaded and all the data for MainTable.SubTable is also loaded. If "Include" is not called, every returned MainTable's SubTable property will return null.
Are there equivalent methods for the Django ORM? If not, what's the default Django behavior for situtions like the above?
|
[
"See this:\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#id4\nYou create a select_related query set to follow relationships and pre-fetch related rows.\nNormally, you don't waste much time doing this until you know that the individual fetches done automagically by the ORM are too slow.\nWhen you simply name a related object field:\nx = MainTable.objects.get( id=\"some Object\" )\ny= x.subTable\n\nThe ORM will do the of the related subTable row. lazily.\nYou can't easily fetch an entire table into memory. QuerySets are \"lazy\" and don't fetch rows until there's no possible excuse. Consider this.\nfor m in MainTable.objects.all():\n y = m.subTable\n if y.someAttribute > 5: \n break\n\nThen you may not actually need all the objects in MainTable. The query set is ready to fetch them. It just doesn't actually fetch them all. That's why we don't generally do anything more than x.subTable and leave it to the ORM to fetch the row as needed.\nOnce in a while you can prove that it's too slow. Then you can do MainTable.objects.select_related()... and force navigation to rows in other tables.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"django_models",
"linq",
"linq_to_sql",
"python"
] |
stackoverflow_0002189122_django_django_models_linq_linq_to_sql_python.txt
|
Q:
What are the advantages, if any, to using mako's or pylon's form handlers instead of coding the form manually?
Trying to decide if I should be using mako to handle the forms in my application or not. Thanks for the input.
A:
It'll save you a lot of time (even if you use them just during development) to use Pylons built-in form handling. Later if you want to strip them out and hard code a full form for each page, you can but I'd use the built-in one and find ways to customize within it before going completely manual about it.
|
What are the advantages, if any, to using mako's or pylon's form handlers instead of coding the form manually?
|
Trying to decide if I should be using mako to handle the forms in my application or not. Thanks for the input.
|
[
"It'll save you a lot of time (even if you use them just during development) to use Pylons built-in form handling. Later if you want to strip them out and hard code a full form for each page, you can but I'd use the built-in one and find ways to customize within it before going completely manual about it.\n"
] |
[
1
] |
[] |
[] |
[
"mako",
"pylons",
"python"
] |
stackoverflow_0002189432_mako_pylons_python.txt
|
Q:
Writing good tests for Django applications
I've never written any tests in my life, but I'd like to start writing tests for my Django projects. I've read some articles about tests and decided to try to write some tests for an extremely simple Django app or a start.
The app has two views (a list view, and a detail view) and a model with four fields:
class News(models.Model):
title = models.CharField(max_length=250)
content = models.TextField()
pub_date = models.DateTimeField(default=datetime.datetime.now)
slug = models.SlugField(unique=True)
I would like to show you my tests.py file and ask:
Does it make sense?
Am I even testing for the right things?
Are there best practices I'm not following, and you could point me to?
my tests.py (it contains 11 tests):
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
import datetime
from someproject.myapp.models import News
class viewTest(TestCase):
def setUp(self):
self.test_title = u'Test title: bąrekść'
self.test_content = u'This is a content 156'
self.test_slug = u'test-title-bareksc'
self.test_pub_date = datetime.datetime.today()
self.test_item = News.objects.create(
title=self.test_title,
content=self.test_content,
slug=self.test_slug,
pub_date=self.test_pub_date,
)
client = Client()
self.response_detail = client.get(self.test_item.get_absolute_url())
self.response_index = client.get(reverse('the-list-view'))
def test_detail_status_code(self):
"""
HTTP status code for the detail view
"""
self.failUnlessEqual(self.response_detail.status_code, 200)
def test_list_status_code(self):
"""
HTTP status code for the list view
"""
self.failUnlessEqual(self.response_index.status_code, 200)
def test_list_numer_of_items(self):
self.failUnlessEqual(len(self.response_index.context['object_list']), 1)
def test_detail_title(self):
self.failUnlessEqual(self.response_detail.context['object'].title, self.test_title)
def test_list_title(self):
self.failUnlessEqual(self.response_index.context['object_list'][0].title, self.test_title)
def test_detail_content(self):
self.failUnlessEqual(self.response_detail.context['object'].content, self.test_content)
def test_list_content(self):
self.failUnlessEqual(self.response_index.context['object_list'][0].content, self.test_content)
def test_detail_slug(self):
self.failUnlessEqual(self.response_detail.context['object'].slug, self.test_slug)
def test_list_slug(self):
self.failUnlessEqual(self.response_index.context['object_list'][0].slug, self.test_slug)
def test_detail_template(self):
self.assertContains(self.response_detail, self.test_title)
self.assertContains(self.response_detail, self.test_content)
def test_list_template(self):
self.assertContains(self.response_index, self.test_title)
A:
I am not perfect in testing but a few thoughts:
Basically you should test every function, method, class, whatever, that you have written by yourself.
This implies that you don't have to test functions, classes, etc. which the framework provides.
That said, a quick check of your test functions:
test_detail_status_code and test_list_status_code:
Ok to check whether you have configured the routing properly or not. Even more important when you provide your own implementation of get_absolute_url().
test_list_numer_of_items:
Ok if a certain number of items should be returned by the view. Not necessary if the number is not important (i.e. arbitrary).
test_detail_template and test_list_template:
Ok to check whether template variables are correctly set.
All the other functions: Not necessary.
What your are basically testing here is whether the ORM worked properly, whether lists work as expected and whether object properties can be accessed (or not). As long as you don't change e.g. the save() method of a model and/or provide your custom logic, I would not test this. You should trust the framework developers that this works properly.
You only should have to test what you have (over)written.
The model classes are maybe a special case. You basically have to test them, as I said, if you provide custom logic. But you should also test them against your requirements. E.g. it could be that a field is not allowed to be null (or that it has to be a certain datatype, like integer). So you should test that storing an object fails, if it has a null value in this field.
This does not test the ORM for correctly following your specification but test that the specification still fulfills your requirements. It might be that you change the model and change some settings (by chance or because you forgot about the requirements).
But you don't have to test e.g. methods like save() or wether you can access a property.
Of course when you use buggy third party code... well things can be different. But as Django uses the test framework itself to verify that everything is working, I would assume it is working.
To sum up:
Test against your requirements, test your own code.
This is only my point of view. Maybe others have better proposals.
A:
Break your tests into two completely separate kinds.
Model tests. Put these in your models.py file with your model. These tests will exercise the methods in your model classes. You can do simple CRUD (Create, Retrieve, Update, Delete) to simply prove that your model works. Don't test every attribute. Do test field defaults and save() rules if you're curious.
For your example, create a TestNews class that creates, gets, updates and deletes a News item. Be sure to test the default date results. This class should be short and to the point. You can, if your application requires it, test various kinds of filter processing. Your unit test code can (and should) provide examples of the "right" way to filter News.
UI Tests. Put these in a separate tests.py file. These tests will test the view functions and templates.
Name the TestCase with the "condition" you're creating. "TestNotLoggedIn". "TestLoggedIn". "TestNoValidThis". "TestNotAllowedToDoThat". Your setUp will do the login and any other steps required to establish the required condition.
Name each test method with the action and result. "test_get_noquery_should_list", "test_post_should_validate_with_errors", "test_get_query_should_detail".
|
Writing good tests for Django applications
|
I've never written any tests in my life, but I'd like to start writing tests for my Django projects. I've read some articles about tests and decided to try to write some tests for an extremely simple Django app or a start.
The app has two views (a list view, and a detail view) and a model with four fields:
class News(models.Model):
title = models.CharField(max_length=250)
content = models.TextField()
pub_date = models.DateTimeField(default=datetime.datetime.now)
slug = models.SlugField(unique=True)
I would like to show you my tests.py file and ask:
Does it make sense?
Am I even testing for the right things?
Are there best practices I'm not following, and you could point me to?
my tests.py (it contains 11 tests):
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
import datetime
from someproject.myapp.models import News
class viewTest(TestCase):
def setUp(self):
self.test_title = u'Test title: bąrekść'
self.test_content = u'This is a content 156'
self.test_slug = u'test-title-bareksc'
self.test_pub_date = datetime.datetime.today()
self.test_item = News.objects.create(
title=self.test_title,
content=self.test_content,
slug=self.test_slug,
pub_date=self.test_pub_date,
)
client = Client()
self.response_detail = client.get(self.test_item.get_absolute_url())
self.response_index = client.get(reverse('the-list-view'))
def test_detail_status_code(self):
"""
HTTP status code for the detail view
"""
self.failUnlessEqual(self.response_detail.status_code, 200)
def test_list_status_code(self):
"""
HTTP status code for the list view
"""
self.failUnlessEqual(self.response_index.status_code, 200)
def test_list_numer_of_items(self):
self.failUnlessEqual(len(self.response_index.context['object_list']), 1)
def test_detail_title(self):
self.failUnlessEqual(self.response_detail.context['object'].title, self.test_title)
def test_list_title(self):
self.failUnlessEqual(self.response_index.context['object_list'][0].title, self.test_title)
def test_detail_content(self):
self.failUnlessEqual(self.response_detail.context['object'].content, self.test_content)
def test_list_content(self):
self.failUnlessEqual(self.response_index.context['object_list'][0].content, self.test_content)
def test_detail_slug(self):
self.failUnlessEqual(self.response_detail.context['object'].slug, self.test_slug)
def test_list_slug(self):
self.failUnlessEqual(self.response_index.context['object_list'][0].slug, self.test_slug)
def test_detail_template(self):
self.assertContains(self.response_detail, self.test_title)
self.assertContains(self.response_detail, self.test_content)
def test_list_template(self):
self.assertContains(self.response_index, self.test_title)
|
[
"I am not perfect in testing but a few thoughts:\n\nBasically you should test every function, method, class, whatever, that you have written by yourself.\n\nThis implies that you don't have to test functions, classes, etc. which the framework provides. \nThat said, a quick check of your test functions:\n\ntest_detail_status_code and test_list_status_code:\nOk to check whether you have configured the routing properly or not. Even more important when you provide your own implementation of get_absolute_url().\ntest_list_numer_of_items:\nOk if a certain number of items should be returned by the view. Not necessary if the number is not important (i.e. arbitrary).\ntest_detail_template and test_list_template:\nOk to check whether template variables are correctly set.\nAll the other functions: Not necessary.\nWhat your are basically testing here is whether the ORM worked properly, whether lists work as expected and whether object properties can be accessed (or not). As long as you don't change e.g. the save() method of a model and/or provide your custom logic, I would not test this. You should trust the framework developers that this works properly.\n\nYou only should have to test what you have (over)written.\nThe model classes are maybe a special case. You basically have to test them, as I said, if you provide custom logic. But you should also test them against your requirements. E.g. it could be that a field is not allowed to be null (or that it has to be a certain datatype, like integer). So you should test that storing an object fails, if it has a null value in this field.\nThis does not test the ORM for correctly following your specification but test that the specification still fulfills your requirements. It might be that you change the model and change some settings (by chance or because you forgot about the requirements).\nBut you don't have to test e.g. methods like save() or wether you can access a property.\nOf course when you use buggy third party code... well things can be different. But as Django uses the test framework itself to verify that everything is working, I would assume it is working.\nTo sum up:\nTest against your requirements, test your own code.\nThis is only my point of view. Maybe others have better proposals.\n",
"Break your tests into two completely separate kinds.\n\nModel tests. Put these in your models.py file with your model. These tests will exercise the methods in your model classes. You can do simple CRUD (Create, Retrieve, Update, Delete) to simply prove that your model works. Don't test every attribute. Do test field defaults and save() rules if you're curious.\nFor your example, create a TestNews class that creates, gets, updates and deletes a News item. Be sure to test the default date results. This class should be short and to the point. You can, if your application requires it, test various kinds of filter processing. Your unit test code can (and should) provide examples of the \"right\" way to filter News.\nUI Tests. Put these in a separate tests.py file. These tests will test the view functions and templates.\n\nName the TestCase with the \"condition\" you're creating. \"TestNotLoggedIn\". \"TestLoggedIn\". \"TestNoValidThis\". \"TestNotAllowedToDoThat\". Your setUp will do the login and any other steps required to establish the required condition.\nName each test method with the action and result. \"test_get_noquery_should_list\", \"test_post_should_validate_with_errors\", \"test_get_query_should_detail\".\n\n\n"
] |
[
18,
6
] |
[] |
[] |
[
"django",
"django_testing",
"python",
"unit_testing"
] |
stackoverflow_0002188551_django_django_testing_python_unit_testing.txt
|
Q:
What is a good (fastest, least broken, etc) way to implement JSON in Python?
There seems to be a handful of JSON libraries out there for Python even though Python has a built-in library. One even claims to be built according to http://www.json.org spec (which caused me to think 'hmmm, is Python's built in library not built fully to spec?', so I find myself here to ask what others have found when trying out different libraries. Is there any difference?
I will be using it for a Django-based web AJAX API (I know there are Django apps for this, but I want to get at the root of this before I just grab an app).
A:
The built in library is fine most of the time although occasionally you can get issues to do with character encoding.
There is cjson if you have performance issues to deal with.
Personally, I just use simplejson - for no particular reason.
A:
Python < 2.6 did not include json module. The presence of multiple JSON implementations says nothing about the quality of the built-in module and everything about the history of having no built-in json.
I suggest that your assumption (multiple implemntations means low quality in the library) is false.
A:
The built-in module json works perfect. If you have to use an earlier python, use simplejson, a third-party module (which is exactly the same interface). These have the serialization interface you expect from Python and are widely used.
(simple)json by default has some very minor extensions of the JSON standard. You can read about these in the documentation for json and disable them if you want to for some reason.
|
What is a good (fastest, least broken, etc) way to implement JSON in Python?
|
There seems to be a handful of JSON libraries out there for Python even though Python has a built-in library. One even claims to be built according to http://www.json.org spec (which caused me to think 'hmmm, is Python's built in library not built fully to spec?', so I find myself here to ask what others have found when trying out different libraries. Is there any difference?
I will be using it for a Django-based web AJAX API (I know there are Django apps for this, but I want to get at the root of this before I just grab an app).
|
[
"The built in library is fine most of the time although occasionally you can get issues to do with character encoding.\nThere is cjson if you have performance issues to deal with.\nPersonally, I just use simplejson - for no particular reason.\n",
"Python < 2.6 did not include json module. The presence of multiple JSON implementations says nothing about the quality of the built-in module and everything about the history of having no built-in json. \nI suggest that your assumption (multiple implemntations means low quality in the library) is false. \n",
"The built-in module json works perfect. If you have to use an earlier python, use simplejson, a third-party module (which is exactly the same interface). These have the serialization interface you expect from Python and are widely used. \n(simple)json by default has some very minor extensions of the JSON standard. You can read about these in the documentation for json and disable them if you want to for some reason.\n"
] |
[
3,
3,
1
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0002189471_json_python.txt
|
Q:
What do I do with a Concrete Syntax Tree?
I'm using pyPEG to create a parse tree for a simple grammar. The tree is represented using lists and tuples. Here's an example:
[('command',
[('directives',
[('directive',
[('name', 'retrieve')]),
('directive',
[('name', 'commit')])]),
('filename',
[('name', 'f30502')])])]
My question is what do I do with it at this point? I know a lot depends on what I am trying to do, but I haven't been able to find much about consuming/using parse trees, only creating them. Does anyone have any pointers to references I might use?
Thanks for your help.
A:
CSTs (concrete syntax trees) are quite hard to work with for some reasons. Therefore they're commonly converted to ASTs (abstract syntax tree) for further processing (details in the same article). For instance, the Python compiler (the component that turns Python source code into Python VM bytecode) translates CSTs to ASTs as part of its work.
Now, it really does strongly depend on your final goal. What are you parsing? What do you want to do with it? If you're re-creating a classical compilation flow, converting to an AST is probably a good way to proceed. Otherwise, you may find the CST enough - it all depends on what you need.
|
What do I do with a Concrete Syntax Tree?
|
I'm using pyPEG to create a parse tree for a simple grammar. The tree is represented using lists and tuples. Here's an example:
[('command',
[('directives',
[('directive',
[('name', 'retrieve')]),
('directive',
[('name', 'commit')])]),
('filename',
[('name', 'f30502')])])]
My question is what do I do with it at this point? I know a lot depends on what I am trying to do, but I haven't been able to find much about consuming/using parse trees, only creating them. Does anyone have any pointers to references I might use?
Thanks for your help.
|
[
"CSTs (concrete syntax trees) are quite hard to work with for some reasons. Therefore they're commonly converted to ASTs (abstract syntax tree) for further processing (details in the same article). For instance, the Python compiler (the component that turns Python source code into Python VM bytecode) translates CSTs to ASTs as part of its work.\nNow, it really does strongly depend on your final goal. What are you parsing? What do you want to do with it? If you're re-creating a classical compilation flow, converting to an AST is probably a good way to proceed. Otherwise, you may find the CST enough - it all depends on what you need.\n"
] |
[
4
] |
[] |
[] |
[
"concrete_syntax_tree",
"parsing",
"python"
] |
stackoverflow_0002189330_concrete_syntax_tree_parsing_python.txt
|
Q:
How do I reply to an email using the Python imaplib and include the original message?
I'm currently using imaplib to fetch email messages from a server and process the contents and attachments.
I'd like to reply to the messages with a status/error message and links to the resulting generated content on my site if they can be processed. This should include the original message but should drop any attachments (which will be large) and preferably replace them with just their filenames/sizes.
Since I'm already walking the MIME message parts, I'm assuming what I need to do is build a new MIME message tree containing a copy of the original message and delete/replace the attachment nodes.
Before I start down that path, I was hoping someone can give me some tips. Is there any kind of library function to do this? Any kind of standard behavior I should stick to?
I currently know of/am using the imaplib, smtplib and email modules and but may have missed something obvious in there. This is running in Django too, so can use anything in django.core.email if that makes it easier.
A:
The original MIME tree structure of the incoming message is as follows (using email.iterators._structure(msg)):
multipart/mixed
text/html (message)
application/octet-stream (attachment 1)
application/octet-stream (attachment 2)
Replying via GMail results in the following structure:
multipart/alternative
text/plain
text/html
I.e. they aren't being as smart as I thought, just discarding the attachments (good) and providing text and HTML versions that explicitly restructure the "quoted content."
I'm beginning to think that's all I should do too, just reply with a simple message as after discarding the attachments there's not much point in keeping the original message.
Still, might as well answer my original question since I've figured out how to now anyway.
First, replace all the attachments in the original message with text/plain placeholders:
import email
original = email.message_from_string( ... )
for part in original.walk():
if (part.get('Content-Disposition')
and part.get('Content-Disposition').startswith("attachment")):
part.set_type("text/plain")
part.set_payload("Attachment removed: %s (%s, %d bytes)"
%(part.get_filename(),
part.get_content_type(),
len(part.get_payload(decode=True))))
del part["Content-Disposition"]
del part["Content-Transfer-Encoding"]
Then create a reply message:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.message import MIMEMessage
new = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach( MIMEText("reply body text", "plain") )
body.attach( MIMEText("<html>reply body text</html>", "html") )
new.attach(body)
new["Message-ID"] = email.utils.make_msgid()
new["In-Reply-To"] = original["Message-ID"]
new["References"] = original["Message-ID"]
new["Subject"] = "Re: "+original["Subject"]
new["To"] = original["Reply-To"] or original["From"]
new["From"] = "me@mysite.com"
Then attach the original MIME message object and send:
new.attach( MIMEMessage(original) )
s = smtplib.SMTP()
s.sendmail("me@mysite.com", [new["To"]], new.as_string())
s.quit()
The resulting structure is:
multipart/mixed
multipart/alternative
text/plain
text/html
message/rfc822
multipart/mixed
text/html
text/plain
text/plain
Or it's a bit simpler using Django:
from django.core.mail import EmailMultiAlternatives
from email.mime.message import MIMEMessage
new = EmailMultiAlternatives("Re: "+original["Subject"],
"reply body text",
"me@mysite.com", # from
[original["Reply-To"] or original["From"]], # to
headers = {'Reply-To': "me@mysite.com",
"In-Reply-To": original["Message-ID"],
"References": original["Message-ID"]})
new.attach_alternative("<html>reply body text</html>", "text/html")
new.attach( MIMEMessage(original) ) # attach original message
new.send()
The result ends (in GMail at least) showing the original message as "---- Forwarded message ----" which isn't quite what I was after, but the general idea works and I hope this answer helps someone trying to figure out how to fiddle with MIME messages.
|
How do I reply to an email using the Python imaplib and include the original message?
|
I'm currently using imaplib to fetch email messages from a server and process the contents and attachments.
I'd like to reply to the messages with a status/error message and links to the resulting generated content on my site if they can be processed. This should include the original message but should drop any attachments (which will be large) and preferably replace them with just their filenames/sizes.
Since I'm already walking the MIME message parts, I'm assuming what I need to do is build a new MIME message tree containing a copy of the original message and delete/replace the attachment nodes.
Before I start down that path, I was hoping someone can give me some tips. Is there any kind of library function to do this? Any kind of standard behavior I should stick to?
I currently know of/am using the imaplib, smtplib and email modules and but may have missed something obvious in there. This is running in Django too, so can use anything in django.core.email if that makes it easier.
|
[
"The original MIME tree structure of the incoming message is as follows (using email.iterators._structure(msg)):\nmultipart/mixed\n text/html (message)\n application/octet-stream (attachment 1)\n application/octet-stream (attachment 2)\n\nReplying via GMail results in the following structure:\nmultipart/alternative\n text/plain\n text/html\n\nI.e. they aren't being as smart as I thought, just discarding the attachments (good) and providing text and HTML versions that explicitly restructure the \"quoted content.\"\nI'm beginning to think that's all I should do too, just reply with a simple message as after discarding the attachments there's not much point in keeping the original message.\nStill, might as well answer my original question since I've figured out how to now anyway.\nFirst, replace all the attachments in the original message with text/plain placeholders:\nimport email\n\noriginal = email.message_from_string( ... )\n\nfor part in original.walk():\n if (part.get('Content-Disposition')\n and part.get('Content-Disposition').startswith(\"attachment\")):\n\n part.set_type(\"text/plain\")\n part.set_payload(\"Attachment removed: %s (%s, %d bytes)\"\n %(part.get_filename(), \n part.get_content_type(), \n len(part.get_payload(decode=True))))\n del part[\"Content-Disposition\"]\n del part[\"Content-Transfer-Encoding\"]\n\nThen create a reply message:\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.message import MIMEMessage\n\nnew = MIMEMultipart(\"mixed\")\nbody = MIMEMultipart(\"alternative\")\nbody.attach( MIMEText(\"reply body text\", \"plain\") )\nbody.attach( MIMEText(\"<html>reply body text</html>\", \"html\") )\nnew.attach(body)\n\nnew[\"Message-ID\"] = email.utils.make_msgid()\nnew[\"In-Reply-To\"] = original[\"Message-ID\"]\nnew[\"References\"] = original[\"Message-ID\"]\nnew[\"Subject\"] = \"Re: \"+original[\"Subject\"]\nnew[\"To\"] = original[\"Reply-To\"] or original[\"From\"]\nnew[\"From\"] = \"me@mysite.com\"\n\nThen attach the original MIME message object and send:\nnew.attach( MIMEMessage(original) )\n\ns = smtplib.SMTP()\ns.sendmail(\"me@mysite.com\", [new[\"To\"]], new.as_string())\ns.quit()\n\nThe resulting structure is:\nmultipart/mixed\n multipart/alternative\n text/plain\n text/html\n message/rfc822\n multipart/mixed\n text/html\n text/plain\n text/plain\n\nOr it's a bit simpler using Django:\nfrom django.core.mail import EmailMultiAlternatives\nfrom email.mime.message import MIMEMessage\n\nnew = EmailMultiAlternatives(\"Re: \"+original[\"Subject\"],\n \"reply body text\", \n \"me@mysite.com\", # from\n [original[\"Reply-To\"] or original[\"From\"]], # to\n headers = {'Reply-To': \"me@mysite.com\",\n \"In-Reply-To\": original[\"Message-ID\"],\n \"References\": original[\"Message-ID\"]})\nnew.attach_alternative(\"<html>reply body text</html>\", \"text/html\")\nnew.attach( MIMEMessage(original) ) # attach original message\nnew.send()\n\nThe result ends (in GMail at least) showing the original message as \"---- Forwarded message ----\" which isn't quite what I was after, but the general idea works and I hope this answer helps someone trying to figure out how to fiddle with MIME messages.\n"
] |
[
22
] |
[] |
[] |
[
"django",
"email",
"imaplib",
"mime",
"python"
] |
stackoverflow_0002182196_django_email_imaplib_mime_python.txt
|
Q:
getting the id of a created record in SQLAlchemy
How can I get the id of the created record in SQLAlchemy?
I'm doing:
engine.execute("insert into users values (1,'john')")
A:
When you execute a plain text statement, you're at the mercy of the DBAPI you're using as to whether or not the new PK value is available and via what means. With SQlite and MySQL DBAPIs you'll have it as result.lastrowid, which just gives you the value of .lastrowid for the cursor. With PG, Oracle, etc., there's no ".lastrowid" - as someone else said you can use "RETURNING" for those in which case results are available via result.fetchone() (although using RETURNING with oracle, again not taking advantage of SQLAlchemy expression constructs, requires several awkward steps), or if RETURNING isn't available you can use direct sequence access (NEXTVAL in pg), or a "post fetch" operation (CURRVAL in PG, @@identity or scope_identity() in MSSQL).
Sounds complicated right ? That's why you're better off using table.insert(). SQLAlchemy's primary system of providing newly generated PKs is designed to work with these constructs. One you're there, the result.last_inserted_ids() method gives you the newly generated (possibly composite) PK in all cases, regardless of backend. The above methods of .lastrowid, sequence execution, RETURNING etc. are all dealt with for you (0.6 uses RETURNING when available).
A:
There's an extra clause you can add: RETURNING
ie
INSERT INTO users (name, address) VALUES ('richo', 'beaconsfield') RETURNING id
Then just retrieve a row like your insert was a SELECT statement.
|
getting the id of a created record in SQLAlchemy
|
How can I get the id of the created record in SQLAlchemy?
I'm doing:
engine.execute("insert into users values (1,'john')")
|
[
"When you execute a plain text statement, you're at the mercy of the DBAPI you're using as to whether or not the new PK value is available and via what means. With SQlite and MySQL DBAPIs you'll have it as result.lastrowid, which just gives you the value of .lastrowid for the cursor. With PG, Oracle, etc., there's no \".lastrowid\" - as someone else said you can use \"RETURNING\" for those in which case results are available via result.fetchone() (although using RETURNING with oracle, again not taking advantage of SQLAlchemy expression constructs, requires several awkward steps), or if RETURNING isn't available you can use direct sequence access (NEXTVAL in pg), or a \"post fetch\" operation (CURRVAL in PG, @@identity or scope_identity() in MSSQL).\nSounds complicated right ? That's why you're better off using table.insert(). SQLAlchemy's primary system of providing newly generated PKs is designed to work with these constructs. One you're there, the result.last_inserted_ids() method gives you the newly generated (possibly composite) PK in all cases, regardless of backend. The above methods of .lastrowid, sequence execution, RETURNING etc. are all dealt with for you (0.6 uses RETURNING when available).\n",
"There's an extra clause you can add: RETURNING\nie\nINSERT INTO users (name, address) VALUES ('richo', 'beaconsfield') RETURNING id\n\nThen just retrieve a row like your insert was a SELECT statement.\n"
] |
[
14,
3
] |
[] |
[] |
[
"insert",
"python",
"sqlalchemy"
] |
stackoverflow_0002188844_insert_python_sqlalchemy.txt
|
Q:
Making wxPython GUI launch on a different screen from Eclipse
I currently have a dual-monitor setup with Eclipse on monitor 2. When I run the code that launches the wxPython GUI, I would like for this GUI to appear on monitor 1. Currently, the GUI consistently appears on monitor 2, covering Eclipse, and I have to drag it to monitor 1 every time. Is there a solution to this problem -- either a configuration change I can make in Eclipse or some addition I can make to the GUI code?
A:
I'm not entirely sure, but I think I remember reading something about windows sticking to the same monitor as the process that spawned them. Therefore, it might be a worthwhile experiment to edit your code in eclipse (on monitor 2) and have a command prompt window open on monitor 1 from which you can run the python code. Since it will be command prompt window that is spawning the GUI, it should appear on monitor 1 as you would like.
This is just a hacky solution (that too, only if I remember correctly). As for an option in eclipse, I have no idea about that. I only posted a thought because nobody has replied yet.
You might also want to try posting on superUser, perhaps someone there can help.
A:
The best kludge I found was the Kubuntu global shortcut "Ctrl-Shift-Space". This moves a window to the other screen, mitigating the hassle of dragging with the mouse.
A:
Kludge #2: If I run the code from Eclipse on screen 2 then click someplace on screen 1 before the GUI appears, the GUI will appear on screen 1.
|
Making wxPython GUI launch on a different screen from Eclipse
|
I currently have a dual-monitor setup with Eclipse on monitor 2. When I run the code that launches the wxPython GUI, I would like for this GUI to appear on monitor 1. Currently, the GUI consistently appears on monitor 2, covering Eclipse, and I have to drag it to monitor 1 every time. Is there a solution to this problem -- either a configuration change I can make in Eclipse or some addition I can make to the GUI code?
|
[
"I'm not entirely sure, but I think I remember reading something about windows sticking to the same monitor as the process that spawned them. Therefore, it might be a worthwhile experiment to edit your code in eclipse (on monitor 2) and have a command prompt window open on monitor 1 from which you can run the python code. Since it will be command prompt window that is spawning the GUI, it should appear on monitor 1 as you would like.\nThis is just a hacky solution (that too, only if I remember correctly). As for an option in eclipse, I have no idea about that. I only posted a thought because nobody has replied yet.\nYou might also want to try posting on superUser, perhaps someone there can help.\n",
"The best kludge I found was the Kubuntu global shortcut \"Ctrl-Shift-Space\". This moves a window to the other screen, mitigating the hassle of dragging with the mouse.\n",
"Kludge #2: If I run the code from Eclipse on screen 2 then click someplace on screen 1 before the GUI appears, the GUI will appear on screen 1.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"eclipse",
"python",
"wxpython"
] |
stackoverflow_0002174904_eclipse_python_wxpython.txt
|
Q:
What is the python equivalent of the Perl pattern to track if something has already been seen?
In Perl, one can do the following
for (@foo) {
# do something
next if $seen{$_}++;
}
I would like to be able to do the equivalent in Python, that is to skip a block if it has been executed once.
A:
seen = set()
for x in foo:
if x in seen:
continue
seen.add(x)
# do something
See the set documentation for more information.
Also, the examples at the bottom of the itertools module documentation contains a unique_everseen generator that you can use like this:
for x in unique_everseen(foo):
# do something
A:
seen={}
for item in foo:
if seen.has_key(item):
seen[item]+=1
continue # continue is optional, just to illustrate the "next" in Perl
else:
seen[item]=1
A:
If you don't care about the order of the things in foo, and only that the unique items are iterated over, then the solution is much simpler.
for x in set(foo):
do something
|
What is the python equivalent of the Perl pattern to track if something has already been seen?
|
In Perl, one can do the following
for (@foo) {
# do something
next if $seen{$_}++;
}
I would like to be able to do the equivalent in Python, that is to skip a block if it has been executed once.
|
[
"seen = set()\nfor x in foo:\n if x in seen:\n continue\n seen.add(x)\n # do something\n\nSee the set documentation for more information.\nAlso, the examples at the bottom of the itertools module documentation contains a unique_everseen generator that you can use like this:\nfor x in unique_everseen(foo):\n # do something\n\n",
"seen={}\nfor item in foo:\n if seen.has_key(item):\n seen[item]+=1\n continue # continue is optional, just to illustrate the \"next\" in Perl\n else:\n seen[item]=1\n\n",
"If you don't care about the order of the things in foo, and only that the unique items are iterated over, then the solution is much simpler.\nfor x in set(foo):\n do something\n\n"
] |
[
11,
1,
1
] |
[] |
[] |
[
"perl",
"python"
] |
stackoverflow_0002188863_perl_python.txt
|
Q:
python normalized path gets reset in a for loop
I am trying to get a normalized path on windows. The paths are stored in a list and i am looping over those as follows:
>>> lst = ['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> lst
['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> for pth in lst:
... print pth
...
C:\
C:\Windows
C:\Program Files
Notice that it has removed one backslash from the output C:\ should be C:\.
The output doesn't change even when I normalize the path in the loop as below:
>>> import os
>>> for pth in lst:
... print os.path.normpath(pth)
...
C:\
C:\Windows
C:\Program Files
Can anyone suggest a fix? Thanks
Update
seems like the suggestions about the raw string is a better way to handle this. But how to specify the string as a raw string within a for loop. Example:
for pth in lst:
raw_str = rpth
Obviously the above doesn't work . How do I achieve this? r'path/to/file' ?
A:
The double slash is simply string escaping - you need to escape slashes in string literals. Printing lst[0] before the loop will print it without the slash. If you want to really include a double slash in your literal, use the raw string syntax:
>>> lst = ['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> lst[0]
'C:\\'
>>> print lst[0]
C:\
>>> lst2 = [r'C:\\', r'C:\\Windows', r'C:\\Program Files']
>>> lst2[0]
'C:\\\\'
>>> print lst2[0]
C:\\
EDIT: If you want to double the slashes, you can do a simple string replace:
>>> x = 'C:\\Windows'
>>> print x
C:\Windows
>>> x = x.replace('\\', '\\\\')
>>> print x
C:\\Windows
A:
In Python, when you say
>>> s = 'C:\\'
s contains three characters: C, : and \. This can be easily seen by:
>>> len(s)
3
In Python, as in many other languages, a backslash is used to escape certain characters. For example, a newline is \n, a character with value 0 is \x00, etc. A "real" backslash is \\. So, to actually get two backslashes, you need to escape both, giving:
>>> s = 'C:\\\\'
But, Windows is perfectly happy with / as the separator, so you can do:
>>> s = 'C:/'
A:
\\ is an escape sequence which prints \ as the output. If you want to print C:\\, you'll have to use C:\\\\ as the input string(or use raw strings ...). I can't see why you would want that. Although if you particularly want to, there are different options available.
A:
you need \\? you can use print repr(pth)
A:
If possible, try to use os.path.join() for creating your windows path. You don't have to meddle with slashes as much.
eg
from os.path import join
rootdir="C:\\"
path1 = join(rootdir,"windows")
path2 = join(rootdir,"Program Files")
lst = [ rootdir , path1, path2 ]
A:
Use / for sanity on windows (most programs work with both forms of slashes), but failing that, use r'' whenever you are dealing with backslashed path names.
r'C:\My\Windows\Path'
If you really want double backslashes, then that works too:
r'C:\\My\\Escaped\\Path'
|
python normalized path gets reset in a for loop
|
I am trying to get a normalized path on windows. The paths are stored in a list and i am looping over those as follows:
>>> lst = ['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> lst
['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> for pth in lst:
... print pth
...
C:\
C:\Windows
C:\Program Files
Notice that it has removed one backslash from the output C:\ should be C:\.
The output doesn't change even when I normalize the path in the loop as below:
>>> import os
>>> for pth in lst:
... print os.path.normpath(pth)
...
C:\
C:\Windows
C:\Program Files
Can anyone suggest a fix? Thanks
Update
seems like the suggestions about the raw string is a better way to handle this. But how to specify the string as a raw string within a for loop. Example:
for pth in lst:
raw_str = rpth
Obviously the above doesn't work . How do I achieve this? r'path/to/file' ?
|
[
"The double slash is simply string escaping - you need to escape slashes in string literals. Printing lst[0] before the loop will print it without the slash. If you want to really include a double slash in your literal, use the raw string syntax:\n>>> lst = ['C:\\\\', 'C:\\\\Windows', 'C:\\\\Program Files']\n>>> lst[0]\n'C:\\\\'\n>>> print lst[0]\nC:\\\n>>> lst2 = [r'C:\\\\', r'C:\\\\Windows', r'C:\\\\Program Files']\n>>> lst2[0]\n'C:\\\\\\\\'\n>>> print lst2[0]\nC:\\\\\n\nEDIT: If you want to double the slashes, you can do a simple string replace:\n>>> x = 'C:\\\\Windows'\n>>> print x\nC:\\Windows\n>>> x = x.replace('\\\\', '\\\\\\\\')\n>>> print x\nC:\\\\Windows\n\n",
"In Python, when you say\n>>> s = 'C:\\\\'\n\ns contains three characters: C, : and \\. This can be easily seen by:\n>>> len(s)\n3\n\nIn Python, as in many other languages, a backslash is used to escape certain characters. For example, a newline is \\n, a character with value 0 is \\x00, etc. A \"real\" backslash is \\\\. So, to actually get two backslashes, you need to escape both, giving:\n>>> s = 'C:\\\\\\\\'\n\nBut, Windows is perfectly happy with / as the separator, so you can do:\n>>> s = 'C:/'\n\n",
"\\\\ is an escape sequence which prints \\ as the output. If you want to print C:\\\\, you'll have to use C:\\\\\\\\ as the input string(or use raw strings ...). I can't see why you would want that. Although if you particularly want to, there are different options available.\n",
"you need \\\\? you can use print repr(pth)\n",
"If possible, try to use os.path.join() for creating your windows path. You don't have to meddle with slashes as much.\neg\nfrom os.path import join\nrootdir=\"C:\\\\\"\npath1 = join(rootdir,\"windows\")\npath2 = join(rootdir,\"Program Files\")\nlst = [ rootdir , path1, path2 ]\n\n",
"Use / for sanity on windows (most programs work with both forms of slashes), but failing that, use r'' whenever you are dealing with backslashed path names.\nr'C:\\My\\Windows\\Path'\n\nIf you really want double backslashes, then that works too:\nr'C:\\\\My\\\\Escaped\\\\Path'\n\n"
] |
[
3,
2,
0,
0,
0,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002189863_python_string.txt
|
Q:
Algorithm to detect similar documents in python script
I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?
A:
Bayesian filters have exactly this purpose. That's the techno you'll find in most tools that identify spam.
Example, to detect a language (from http://sebsauvage.net/python/snyppets/#bayesian) :
from reverend.thomas import Bayes
guesser = Bayes()
guesser.train('french','La souris est rentrée dans son trou.')
guesser.train('english','my tailor is rich.')
guesser.train('french','Je ne sais pas si je viendrai demain.')
guesser.train('english','I do not plan to update my website soon.')
>>> print guesser.guess('Jumping out of cliffs it not a good idea.')
[('english', 0.99990000000000001), ('french', 9.9999999999988987e-005)]
>>> print guesser.guess('Demain il fera très probablement chaud.')
[('french', 0.99990000000000001), ('english', 9.9999999999988987e-005)]
But it works to detect any type you will train it for : technical text, songs, jokes, etc. As long as you can provide enought material to let the tool learn what does you document looks like.
A:
If these are pure text documents, or you have a method to extract the text from the documents, you can use a technique called shingling.
You first compute a unique hash for each document. If these are the same, you are done.
If not, you break each document down into smaller chunks. These are your 'shingles.'
Once you have the shingles, you can then compute identity hashes for each shingle and compare the hashes of the shingles to determine if the documents are actually the same.
The other technique you can use is to generate n-grams of the entire documents and compute the number of similar n-grams in each document and produce a weighted score for each document. Basically an n-gram is splitting a word into smaller chunks. 'apple' would become ' a', ' ap', 'app', 'ppl', 'ple', 'le '. (This is technically a 3-gram) This approach can become quite computationally expensive over a large number of documents or over two very large documents. Of course, common n-grams 'the', ' th, 'th ', etc need to be weighted to score them lower.
I've posted about this on my blog and there are some links in the post to a few other articles on the subject Shingling - it's not just for roofers.
Best of luck!
A:
Similarity can be found easily without classification. Try this O(n2) but works fine.
def jaccard_similarity(doc1, doc2):
a = sets(doc1.split())
b = sets(doc2.split())
similarity = float(len(a.intersection(b))*1.0/len(a.union(b))) #similarity belongs to [0,1] 1 means its exact replica.
return similarity
A:
You can use or at last study difflib from Python's stdlib to write your code.
It is very flexible, and has algorithms to find differences between lists of strings, and to point these differences. Then you can use the get_close_matches() to find similar words:
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
It is not the solution but maybe it is a start.
A:
You need to make your question more concrete. If you've already read the fingerprinting papers, you already know the principles at work, so describing common approaches here would not be beneficial. If you haven't, you should also check out papers on "duplicate detection" and various web spam detection related papers that have come out of Stanford, Google, Yahoo, and MS in recent years.
Are you having specific problems with coding the described algorithms?
Trouble getting started?
The first thing I'd probably do is separate the tokenization (the process of extracting "words" or other sensible sequences) from the duplicate detection logic, so that it is easy to plug in different parsers for different languages and keep the duplicate detection piece the same.
A:
There is a rather good talk on neural networks on Google Techtalks that talks about using layered Boltzmann machines to generate feature vectors for documents that can then be used to measure document distance. The main issue is the requirement to have a large sample document set to train the network to discover relevant features.
A:
If you're prepared to index the files that you want to search amongst, Xapian is an excellent engine, and provides Python bindings:
http://xapian.org/
http://xapian.org/docs/bindings/python/
A:
If you are trying to detect the documents that are talking about the same topic, you could try collecting the most frequently used words, throw away the stop words . Documents that have a similar distribution of the most frequently used words are probably talking about similar things. You may need to do some stemming and extend the concept to n-grams if you want higher accuracy. For more advanced techniques, look into machine learning.
A:
I think Jeremy has hit the nail on the head - if you just want to detect if files are different, a hash algorithm like MD5 or SHA1 is a good way to go.
Linus Torvalds' Git source control software uses SHA1 hashing in just this way - to check when files have been modified.
A:
You might want to look into the DustBuster algorithm as outlined in this paper.
From the paper, they're able to detect duplicate pages without even examining the page contents. Of course examining the contents increases the efficacy, but using raw server logs is adequate for the method to detect duplicate pages.
Similar to the recommendation of using MD5 or SHA1 hashes, the DustBuster method largely relies on comparing file size as it primary signal. As simple as it sounds, it's rather effective for an initial first pass.
|
Algorithm to detect similar documents in python script
|
I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?
|
[
"Bayesian filters have exactly this purpose. That's the techno you'll find in most tools that identify spam.\nExample, to detect a language (from http://sebsauvage.net/python/snyppets/#bayesian) :\nfrom reverend.thomas import Bayes\nguesser = Bayes()\nguesser.train('french','La souris est rentrée dans son trou.')\nguesser.train('english','my tailor is rich.')\nguesser.train('french','Je ne sais pas si je viendrai demain.')\nguesser.train('english','I do not plan to update my website soon.')\n\n>>> print guesser.guess('Jumping out of cliffs it not a good idea.')\n[('english', 0.99990000000000001), ('french', 9.9999999999988987e-005)]\n\n>>> print guesser.guess('Demain il fera très probablement chaud.')\n[('french', 0.99990000000000001), ('english', 9.9999999999988987e-005)]\n\nBut it works to detect any type you will train it for : technical text, songs, jokes, etc. As long as you can provide enought material to let the tool learn what does you document looks like.\n",
"If these are pure text documents, or you have a method to extract the text from the documents, you can use a technique called shingling.\nYou first compute a unique hash for each document. If these are the same, you are done.\nIf not, you break each document down into smaller chunks. These are your 'shingles.'\nOnce you have the shingles, you can then compute identity hashes for each shingle and compare the hashes of the shingles to determine if the documents are actually the same.\nThe other technique you can use is to generate n-grams of the entire documents and compute the number of similar n-grams in each document and produce a weighted score for each document. Basically an n-gram is splitting a word into smaller chunks. 'apple' would become ' a', ' ap', 'app', 'ppl', 'ple', 'le '. (This is technically a 3-gram) This approach can become quite computationally expensive over a large number of documents or over two very large documents. Of course, common n-grams 'the', ' th, 'th ', etc need to be weighted to score them lower.\nI've posted about this on my blog and there are some links in the post to a few other articles on the subject Shingling - it's not just for roofers.\nBest of luck!\n",
"Similarity can be found easily without classification. Try this O(n2) but works fine.\ndef jaccard_similarity(doc1, doc2):\n a = sets(doc1.split())\n b = sets(doc2.split())\n similarity = float(len(a.intersection(b))*1.0/len(a.union(b))) #similarity belongs to [0,1] 1 means its exact replica.\n return similarity\n\n",
"You can use or at last study difflib from Python's stdlib to write your code.\nIt is very flexible, and has algorithms to find differences between lists of strings, and to point these differences. Then you can use the get_close_matches() to find similar words:\n>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])\n['apple', 'ape']\n\nIt is not the solution but maybe it is a start.\n",
"You need to make your question more concrete. If you've already read the fingerprinting papers, you already know the principles at work, so describing common approaches here would not be beneficial. If you haven't, you should also check out papers on \"duplicate detection\" and various web spam detection related papers that have come out of Stanford, Google, Yahoo, and MS in recent years.\nAre you having specific problems with coding the described algorithms?\nTrouble getting started?\nThe first thing I'd probably do is separate the tokenization (the process of extracting \"words\" or other sensible sequences) from the duplicate detection logic, so that it is easy to plug in different parsers for different languages and keep the duplicate detection piece the same.\n",
"There is a rather good talk on neural networks on Google Techtalks that talks about using layered Boltzmann machines to generate feature vectors for documents that can then be used to measure document distance. The main issue is the requirement to have a large sample document set to train the network to discover relevant features.\n",
"If you're prepared to index the files that you want to search amongst, Xapian is an excellent engine, and provides Python bindings:\nhttp://xapian.org/\nhttp://xapian.org/docs/bindings/python/\n",
"If you are trying to detect the documents that are talking about the same topic, you could try collecting the most frequently used words, throw away the stop words . Documents that have a similar distribution of the most frequently used words are probably talking about similar things. You may need to do some stemming and extend the concept to n-grams if you want higher accuracy. For more advanced techniques, look into machine learning.\n",
"I think Jeremy has hit the nail on the head - if you just want to detect if files are different, a hash algorithm like MD5 or SHA1 is a good way to go.\nLinus Torvalds' Git source control software uses SHA1 hashing in just this way - to check when files have been modified.\n",
"You might want to look into the DustBuster algorithm as outlined in this paper.\nFrom the paper, they're able to detect duplicate pages without even examining the page contents. Of course examining the contents increases the efficacy, but using raw server logs is adequate for the method to detect duplicate pages.\nSimilar to the recommendation of using MD5 or SHA1 hashes, the DustBuster method largely relies on comparing file size as it primary signal. As simple as it sounds, it's rather effective for an initial first pass.\n"
] |
[
20,
10,
8,
7,
3,
2,
1,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"diff",
"python"
] |
stackoverflow_0000101569_algorithm_diff_python.txt
|
Q:
Execution of python scripts like udev/rules.d, cron.d or /apt/source.d
I use python to patch system settings of linux systems distributed with partimage.
I want to have the following python script structure:
/patch.d/
10_patch_netwok.py
20_patch_hostname.py
...
50_patch_software_xyz.py
InitSystem.py
The InitSytem.py should run the python scripts in /patch.d folder. Following my idea (brainstorm):
files = glob.glob("patch.d/*.py")
files.sort()
for file in files:
execfile(file, ...)
What's the recommend way to load python scripts and run them from another python script?
A:
Python scripts are also python modules, so the best way to load and run them is to simply import them using
__import__('some_module')
This will mean that they run in the same process though. If this is undesirable, then your options would be to use the multi-threading or multi-processing support in python to run each script in a different thread/process to avoid interference, or to use the os.subprocess module to do system calls that run the scripts.
|
Execution of python scripts like udev/rules.d, cron.d or /apt/source.d
|
I use python to patch system settings of linux systems distributed with partimage.
I want to have the following python script structure:
/patch.d/
10_patch_netwok.py
20_patch_hostname.py
...
50_patch_software_xyz.py
InitSystem.py
The InitSytem.py should run the python scripts in /patch.d folder. Following my idea (brainstorm):
files = glob.glob("patch.d/*.py")
files.sort()
for file in files:
execfile(file, ...)
What's the recommend way to load python scripts and run them from another python script?
|
[
"Python scripts are also python modules, so the best way to load and run them is to simply import them using\n__import__('some_module')\n\nThis will mean that they run in the same process though. If this is undesirable, then your options would be to use the multi-threading or multi-processing support in python to run each script in a different thread/process to avoid interference, or to use the os.subprocess module to do system calls that run the scripts.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sysadmin"
] |
stackoverflow_0002190509_python_sysadmin.txt
|
Q:
Multiple Try-Excepts followed by an Else in python
Is there some way to have several consecutive Try-Except clauses that trigger a single Else only if all of them are successful?
As an example:
try:
private.anodization_voltage_meter = Voltmeter(voltage_meter_address.value) #assign voltmeter location
except(visa.VisaIOError): #channel time out
private.logger.warning('Volt Meter is not on or not on this channel')
try:
private.anodization_current_meter = Voltmeter(current_meter_address.value) #assign voltmeter as current meter location
except(visa.VisaIOError): #channel time out
private.logger.warning('Ammeter is not on or not on this channel')
try:
private.sample_thermometer = Voltmeter(sample_thermometer_address.value)#assign voltmeter as thermomter location for sample.
except(visa.VisaIOError): #channel time out
private.logger.warning('Sample Thermometer is not on or not on this channel')
try:
private.heater_thermometer = Voltmeter(heater_thermometer_address.value)#assign voltmeter as thermomter location for heater.
except(visa.VisaIOError): #channel time out
private.logger.warning('Heater Thermometer is not on or not on this channel')
else:
private.logger.info('Meters initialized')
As you can see, you only want to print meters initialized if all of them went off, however as currently written it only depends on the heater thermometer. is there some way to stack these?
A:
Consider breaking the try/except structure into a function that returns True if the call worked and False if it failed, then use e.g. all() to see that they all succeded:
def initfunc(structure, attrname, address, desc):
try:
var = Voltmeter(address.value)
setattr(structure, attrname, var)
return True
except(visa.VisaIOError):
structure.logger.warning('%s is not on or not on this channel' % (desc,))
if all([initfunc(*x) for x in [(private, 'anodization_voltage_meter', voltage_meter_address, 'Volt Meter'), ...]]):
private.logger.info('Meters initialized')
A:
Personally I'd just have a trip variable init_ok or somesuch.
Set it as True, and have all the except clauses set it False, then test at the end?
A:
Try something like this. keeping the original behaviour of not stopping after the first exception
success = True
for meter, address, message in (
('anodization_voltage_meter',voltage_meter_address,'Volt Meter is not on or not on this channel'),
('anodization_current_meter',current_meter_address,'Ammeter is not on or not on this channel'),
('sample_thermometer',sample_thermometer_address,'Sample Thermometer is not on or not on this channel'),
('heater_thermometer',heater_thermometer_address,'Heater Thermometer is not on or not on this channel')):
try:
setattr(private,meter, Voltmeter(address.value):
except (visa.VisaIOError,):
success = False
private.logger.warning(message)
if success: # everything is ok
private.logger.info('Meters initialized')
A:
You can keep a boolean, initialized at the beginning to: everythingOK=True
Then set it to False in all the except blocks and log the final line only if true.
A:
You've got a number of quite similar objects, and in cases like that it's often better to treat them uniformly and use a data-driven approach.
So, I'd start with your ..._meter_address objects. To me they sound like configuration for the meters, so I'd have a class that looks something like this:
class MeterConfiguration(object):
def __init__(self, name, address):
self.name = name
self.address = address
def english_name(self):
"""A readable form of the name for this meter."""
return ' '.join(x.title() for x in self.name.split('_')) + ' Meter'
Perhaps you have some more configuration (currently stored in variables) that could go in here too.
Then, I'd have a summary of all the meters that your program deals with. I'm creating these statically, but it may well be right for you to read all or part of this information from a config file. I've no idea what your addresses look like, so I made something up :)
ALL_METERS = [
MeterConfiguration('anodization_voltage', 'PORT0001'),
MeterConfiguration('anodization_current', 'PORT0002'),
MeterConfiguration('sample_thermometer', 'PORT0003'),
MeterConfiguration('heater_thermometer', 'PORT0004')
]
Cool, now all configuration is in one place, and we can use this to make things uniform and simpler.
private.meters = {}
any_errors = False
for meter in ALL_METERS:
try:
private.meters[meter.name] = Voltmeter(meter.address)
except VisaError:
logging.error('%s not found at %s', meter.english_name(), meter.address)
any_errors = True
if not any_errors:
logging.info('All meters initialized.')
You can use, for example private.meters['anodization_voltage'] to refer to a particular meter, or iterate over the meters dict if you need to do something to them all.
|
Multiple Try-Excepts followed by an Else in python
|
Is there some way to have several consecutive Try-Except clauses that trigger a single Else only if all of them are successful?
As an example:
try:
private.anodization_voltage_meter = Voltmeter(voltage_meter_address.value) #assign voltmeter location
except(visa.VisaIOError): #channel time out
private.logger.warning('Volt Meter is not on or not on this channel')
try:
private.anodization_current_meter = Voltmeter(current_meter_address.value) #assign voltmeter as current meter location
except(visa.VisaIOError): #channel time out
private.logger.warning('Ammeter is not on or not on this channel')
try:
private.sample_thermometer = Voltmeter(sample_thermometer_address.value)#assign voltmeter as thermomter location for sample.
except(visa.VisaIOError): #channel time out
private.logger.warning('Sample Thermometer is not on or not on this channel')
try:
private.heater_thermometer = Voltmeter(heater_thermometer_address.value)#assign voltmeter as thermomter location for heater.
except(visa.VisaIOError): #channel time out
private.logger.warning('Heater Thermometer is not on or not on this channel')
else:
private.logger.info('Meters initialized')
As you can see, you only want to print meters initialized if all of them went off, however as currently written it only depends on the heater thermometer. is there some way to stack these?
|
[
"Consider breaking the try/except structure into a function that returns True if the call worked and False if it failed, then use e.g. all() to see that they all succeded:\ndef initfunc(structure, attrname, address, desc):\n try:\n var = Voltmeter(address.value)\n setattr(structure, attrname, var)\n return True\n except(visa.VisaIOError):\n structure.logger.warning('%s is not on or not on this channel' % (desc,))\n\nif all([initfunc(*x) for x in [(private, 'anodization_voltage_meter', voltage_meter_address, 'Volt Meter'), ...]]):\n private.logger.info('Meters initialized')\n\n",
"Personally I'd just have a trip variable init_ok or somesuch.\nSet it as True, and have all the except clauses set it False, then test at the end?\n",
"Try something like this. keeping the original behaviour of not stopping after the first exception\nsuccess = True\nfor meter, address, message in (\n ('anodization_voltage_meter',voltage_meter_address,'Volt Meter is not on or not on this channel'),\n ('anodization_current_meter',current_meter_address,'Ammeter is not on or not on this channel'),\n ('sample_thermometer',sample_thermometer_address,'Sample Thermometer is not on or not on this channel'),\n ('heater_thermometer',heater_thermometer_address,'Heater Thermometer is not on or not on this channel')):\n try:\n setattr(private,meter, Voltmeter(address.value):\n except (visa.VisaIOError,):\n success = False\n private.logger.warning(message)\n\nif success: # everything is ok\n private.logger.info('Meters initialized')\n\n",
"You can keep a boolean, initialized at the beginning to: everythingOK=True\nThen set it to False in all the except blocks and log the final line only if true.\n",
"You've got a number of quite similar objects, and in cases like that it's often better to treat them uniformly and use a data-driven approach.\nSo, I'd start with your ..._meter_address objects. To me they sound like configuration for the meters, so I'd have a class that looks something like this:\nclass MeterConfiguration(object):\n def __init__(self, name, address):\n self.name = name\n self.address = address\n\n def english_name(self):\n \"\"\"A readable form of the name for this meter.\"\"\"\n return ' '.join(x.title() for x in self.name.split('_')) + ' Meter'\n\nPerhaps you have some more configuration (currently stored in variables) that could go in here too.\nThen, I'd have a summary of all the meters that your program deals with. I'm creating these statically, but it may well be right for you to read all or part of this information from a config file. I've no idea what your addresses look like, so I made something up :)\nALL_METERS = [\n MeterConfiguration('anodization_voltage', 'PORT0001'),\n MeterConfiguration('anodization_current', 'PORT0002'),\n MeterConfiguration('sample_thermometer', 'PORT0003'),\n MeterConfiguration('heater_thermometer', 'PORT0004')\n]\n\nCool, now all configuration is in one place, and we can use this to make things uniform and simpler.\nprivate.meters = {}\nany_errors = False\nfor meter in ALL_METERS:\n try:\n private.meters[meter.name] = Voltmeter(meter.address)\n except VisaError:\n logging.error('%s not found at %s', meter.english_name(), meter.address)\n any_errors = True\nif not any_errors:\n logging.info('All meters initialized.')\n\nYou can use, for example private.meters['anodization_voltage'] to refer to a particular meter, or iterate over the meters dict if you need to do something to them all.\n"
] |
[
6,
6,
6,
3,
2
] |
[] |
[] |
[
"exception_handling",
"python"
] |
stackoverflow_0002188754_exception_handling_python.txt
|
Q:
Rebuilding PIL with FreeType
Previously I got a suggedtion to Install the FreeType dev files and rebuild PIL again.
but I have no idea how to do it.
any help will be thanked for
A:
You do it exactly the same way as you did before, but now with the FreeType-dev files installed.
|
Rebuilding PIL with FreeType
|
Previously I got a suggedtion to Install the FreeType dev files and rebuild PIL again.
but I have no idea how to do it.
any help will be thanked for
|
[
"You do it exactly the same way as you did before, but now with the FreeType-dev files installed.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002190711_python.txt
|
Q:
Python: convert script from procedural to OOP style
I wrote this simple Munin plugin to graph average fan speed and I want to redo it to OOP - strictly as a learning exercise. Don't have a clue where to start though. Anyone feel like offering some guidance or even an example of what this script should look like when done. I will use it to redo some other scripts into an OOP style as well; again for learning purposes.
import sys
import subprocess
CMD = "/usr/sbin/omreport chassis fans".split()
# Munin populates sys.argv[1] with "" (an empty argument), lets remove it.
sys.argv = [x for x in sys.argv if x]
if len(sys.argv) > 1:
if sys.argv[1].lower() == "autoconfig":
print "autoconfig"
elif sys.argv[1].lower() == "config":
print "graph_title Average Fan Speed"
print "graph_args --base 1000 -l 0"
print "graph_vlabel speed (RPM)"
print "graph_category Chassis"
print "graph_info This graph shows the average speed of all fans"
print "graph_period second"
print "speed.label speed"
print "speed.info Average fan speed for the five minutes."
else:
try:
data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines()
except OSError, e:
print >> sys.stderr, "Error running '%s', %s" % (" ".join(cmd), e)
sys.exit(1)
count = total = 0
for item in data:
if "Reading" in item:
# Extract variable length fan speed, without regex.
total += int(item.split(":")[1].split()[0])
count += 1
# Sometimes omreport returns zero output if omsa services aren't started.
if not count or not total:
print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.'
print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".'
sys.exit(1)
avg = (total / count)
print "speed.value %s" % avg
A:
You remake it in OOP by identifying code and data that goes together. These you then merge into "classes".
You actual data above seems to be the output of a process.
The code is iterating over it. I guess you can make a class out of that if you want to, but it's a bit silly. :)
So, something like this (obviously completely untested code):
import sys
import subprocess
class Fanspeed(object):
def __init__(self, command):
self.command = command.split()
def average_fan_speed(self):
data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines()
count = total = 0
for item in data:
if "Reading" in item:
# Extract variable length fan speed, without regex.
total += int(item.split(":")[1].split()[0])
count += 1
# Sometimes omreport returns zero output if omsa services aren't started.
if not count or not total:
raise ValueError("I found no fans. Is OMSA services started?"
avg = (total / count)
return % avg
if __main__ == '__main__':
# Munin populates sys.argv[1] with "" (an empty argument), lets remove it.
sys.argv = [x for x in sys.argv if x]
if len(sys.argv) > 1:
if sys.argv[1].lower() == "autoconfig":
print "autoconfig"
elif sys.argv[1].lower() == "config":
print "graph_title Average Fan Speed"
print "graph_args --base 1000 -l 0"
print "graph_vlabel speed (RPM)"
print "graph_category Chassis"
print "graph_info This graph shows the average speed of all fans"
print "graph_period second"
print "speed.label speed"
print "speed.info Average fan speed for the five minutes."
else:
try:
cmd = "/usr/sbin/omreport chassis fans"
fanspeed = Fanspeed(cmd)
average = fanspeed.average_fan_speed()
except OSError, e:
print >> sys.stderr, "Error running '%s', %s" % (cmd, e)
sys.exit(1)
except ValueError, e:
# Sometimes omreport returns zero output if omsa services aren't started.
print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.'
print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".'
sys.exit(1)
But YMMV. It's perhaps a bit clearer.
|
Python: convert script from procedural to OOP style
|
I wrote this simple Munin plugin to graph average fan speed and I want to redo it to OOP - strictly as a learning exercise. Don't have a clue where to start though. Anyone feel like offering some guidance or even an example of what this script should look like when done. I will use it to redo some other scripts into an OOP style as well; again for learning purposes.
import sys
import subprocess
CMD = "/usr/sbin/omreport chassis fans".split()
# Munin populates sys.argv[1] with "" (an empty argument), lets remove it.
sys.argv = [x for x in sys.argv if x]
if len(sys.argv) > 1:
if sys.argv[1].lower() == "autoconfig":
print "autoconfig"
elif sys.argv[1].lower() == "config":
print "graph_title Average Fan Speed"
print "graph_args --base 1000 -l 0"
print "graph_vlabel speed (RPM)"
print "graph_category Chassis"
print "graph_info This graph shows the average speed of all fans"
print "graph_period second"
print "speed.label speed"
print "speed.info Average fan speed for the five minutes."
else:
try:
data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines()
except OSError, e:
print >> sys.stderr, "Error running '%s', %s" % (" ".join(cmd), e)
sys.exit(1)
count = total = 0
for item in data:
if "Reading" in item:
# Extract variable length fan speed, without regex.
total += int(item.split(":")[1].split()[0])
count += 1
# Sometimes omreport returns zero output if omsa services aren't started.
if not count or not total:
print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.'
print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".'
sys.exit(1)
avg = (total / count)
print "speed.value %s" % avg
|
[
"You remake it in OOP by identifying code and data that goes together. These you then merge into \"classes\".\nYou actual data above seems to be the output of a process.\nThe code is iterating over it. I guess you can make a class out of that if you want to, but it's a bit silly. :)\nSo, something like this (obviously completely untested code):\nimport sys\nimport subprocess\n\nclass Fanspeed(object):\n\n def __init__(self, command):\n self.command = command.split()\n\n def average_fan_speed(self):\n data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines()\n\n count = total = 0\n for item in data:\n if \"Reading\" in item:\n # Extract variable length fan speed, without regex.\n total += int(item.split(\":\")[1].split()[0])\n count += 1\n # Sometimes omreport returns zero output if omsa services aren't started.\n if not count or not total:\n raise ValueError(\"I found no fans. Is OMSA services started?\"\n\n avg = (total / count)\n return % avg\n\nif __main__ == '__main__':\n # Munin populates sys.argv[1] with \"\" (an empty argument), lets remove it.\n sys.argv = [x for x in sys.argv if x]\n\n if len(sys.argv) > 1:\n if sys.argv[1].lower() == \"autoconfig\":\n print \"autoconfig\"\n elif sys.argv[1].lower() == \"config\":\n print \"graph_title Average Fan Speed\"\n print \"graph_args --base 1000 -l 0\"\n print \"graph_vlabel speed (RPM)\"\n print \"graph_category Chassis\"\n print \"graph_info This graph shows the average speed of all fans\"\n print \"graph_period second\"\n print \"speed.label speed\"\n print \"speed.info Average fan speed for the five minutes.\"\n else:\n try:\n cmd = \"/usr/sbin/omreport chassis fans\"\n fanspeed = Fanspeed(cmd)\n average = fanspeed.average_fan_speed()\n except OSError, e:\n print >> sys.stderr, \"Error running '%s', %s\" % (cmd, e)\n sys.exit(1)\n except ValueError, e:\n # Sometimes omreport returns zero output if omsa services aren't started.\n print >> sys.stderr, 'Error: \"omreport chassis fans\" returned 0 output.'\n print >> sys.stderr, 'OMSA running? Try: \"srvadmin-services.sh status\".'\n sys.exit(1)\n\nBut YMMV. It's perhaps a bit clearer.\n"
] |
[
3
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0002190880_oop_python.txt
|
Q:
how to correct the misencoded string?
i used mutagen to read the mp3 metadata, since the id3 tag is read in as unicode but in fact it is GBK encoded. how to correct this in python?
audio = EasyID3(name)
title = audio["title"][0]
print title
print repr(title)
produces
µ±Äã¹Âµ¥Äã»áÏëÆðË
u'\xb5\xb1\xc4\xe3\xb9\xc2\xb5\xa5\xc4\xe3\xbb\xe1\xcf\xeb\xc6\xf0\xcb\xad'
but in fact it should be in GBK (chinese).
当你孤单你会想起谁
A:
It looks like the string has been decoded to unicode using the wrong encoding (latin-1).
You need to encode it to a byte string and then decode it back to unicode using the correct encoding.
title = u'\xb5\xb1\xc4\xe3\xb9\xc2\xb5\xa5\xc4\xe3\xbb\xe1\xcf\xeb\xc6\xf0\xcb\xad'
print title.encode('latin-1').decode('gbk')
当你孤单你会想起谁
A:
Looks like it's auto-decoding using latin1. To fix:
>>> title = u'\xb5\xb1\xc4\xe3\xb9\xc2\xb5\xa5\xc4\xe3\xbb\xe1\xcf\xeb\xc6\xf0\xcb\xad'
>>> print title.encode('latin1').decode('GBK')
当你孤单你会想起谁
Tested in Python 2.x but should work fine in 3 as well.
|
how to correct the misencoded string?
|
i used mutagen to read the mp3 metadata, since the id3 tag is read in as unicode but in fact it is GBK encoded. how to correct this in python?
audio = EasyID3(name)
title = audio["title"][0]
print title
print repr(title)
produces
µ±Äã¹Âµ¥Äã»áÏëÆðË
u'\xb5\xb1\xc4\xe3\xb9\xc2\xb5\xa5\xc4\xe3\xbb\xe1\xcf\xeb\xc6\xf0\xcb\xad'
but in fact it should be in GBK (chinese).
当你孤单你会想起谁
|
[
"It looks like the string has been decoded to unicode using the wrong encoding (latin-1).\nYou need to encode it to a byte string and then decode it back to unicode using the correct encoding.\ntitle = u'\\xb5\\xb1\\xc4\\xe3\\xb9\\xc2\\xb5\\xa5\\xc4\\xe3\\xbb\\xe1\\xcf\\xeb\\xc6\\xf0\\xcb\\xad'\nprint title.encode('latin-1').decode('gbk')\n当你孤单你会想起谁\n\n",
"Looks like it's auto-decoding using latin1. To fix:\n>>> title = u'\\xb5\\xb1\\xc4\\xe3\\xb9\\xc2\\xb5\\xa5\\xc4\\xe3\\xbb\\xe1\\xcf\\xeb\\xc6\\xf0\\xcb\\xad'\n>>> print title.encode('latin1').decode('GBK')\n当你孤单你会想起谁\n\nTested in Python 2.x but should work fine in 3 as well.\n"
] |
[
4,
2
] |
[] |
[] |
[
"encoding",
"mp3",
"mutagen",
"python"
] |
stackoverflow_0002190904_encoding_mp3_mutagen_python.txt
|
Q:
Jquery and Django multiple checkbox
I am a beginner in jquery so please bear with me.
I have a jquery function that allows me to select multiple checkboxes and create a string as follows:
function getSelectedVals(){
var tmp =[];
$("input[name='checks']").each(function() {
if ($(this).attr('checked'))
{
checked = ($(this).val());
tmp.push(checked);
}
});
var filters = tmp.join(',');
alert(filters)
return filters;
}
I then call a django view function and pass the string as follows:
selected = getSelectedVals();
var myurl = "/bills/delete/?id=" + selected;
$.ajax({
type: "GET",
url: myurl,
data: selected,
cache: false
});
On the server I have a delete view function that iterates over the checkbox values and manipulates a list.
def delete(request):
global myarray
idx = request.GET[u'id']
listidx = idx.split(',')
for l in listidx:
value = myarray[int(l)]
myarray.remove(value)
return HttpResponse("/bills/jqtut/")
The problem is that on the server all the indexes I am sending as the GET string are not being handled, only half are.
Please help me! Thanks
A:
From what I see, you do it the way around. You should set the same name on all checkboxes. I don't know why do you send it by GET, I'd suggest sending it by POST.
<input type="checkbox" name="vehicle" value="Bike" />
<input type="checkbox" name="vehicle" value="Car" />
<input type="checkbox" name="vehicle" value="Airplane" />
Then, use getlist() method in your view:
def delete(request):
values = request.POST.getlist(u'vehicle')
# Handling goes here.
But anyway, unless you really need to do custom stuff (however special cases are not special enough to break the rules ;), use Django forms. There already is a checkbox list OOTB. I'm not sure why do you even consider using JavaScript in this very case.
A:
firstly, I don't know if you need to manipulate the checkbox values into a string like you are doing. if you allocate them the same name attribute, http (or jQuery's) serialisation will do it for you.
On the Django side use getlist to grab a list, the [] accessor only gets the last value in a list of params.
Http default handling however doesn't send through the values of checkboxes that aren't checked, so you might want to build in some checks that compare the checkboxes you build vs the data you get back.
As Gavoja says above, django forms is probably a good answer for this:
Specifically, you want to use MultipleChoiceField with a CheckboxSelectMultiple widget and the choices as your options:
my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())
also see: In Django is there a way to display choices as checkboxes?
|
Jquery and Django multiple checkbox
|
I am a beginner in jquery so please bear with me.
I have a jquery function that allows me to select multiple checkboxes and create a string as follows:
function getSelectedVals(){
var tmp =[];
$("input[name='checks']").each(function() {
if ($(this).attr('checked'))
{
checked = ($(this).val());
tmp.push(checked);
}
});
var filters = tmp.join(',');
alert(filters)
return filters;
}
I then call a django view function and pass the string as follows:
selected = getSelectedVals();
var myurl = "/bills/delete/?id=" + selected;
$.ajax({
type: "GET",
url: myurl,
data: selected,
cache: false
});
On the server I have a delete view function that iterates over the checkbox values and manipulates a list.
def delete(request):
global myarray
idx = request.GET[u'id']
listidx = idx.split(',')
for l in listidx:
value = myarray[int(l)]
myarray.remove(value)
return HttpResponse("/bills/jqtut/")
The problem is that on the server all the indexes I am sending as the GET string are not being handled, only half are.
Please help me! Thanks
|
[
"From what I see, you do it the way around. You should set the same name on all checkboxes. I don't know why do you send it by GET, I'd suggest sending it by POST.\n<input type=\"checkbox\" name=\"vehicle\" value=\"Bike\" />\n<input type=\"checkbox\" name=\"vehicle\" value=\"Car\" />\n<input type=\"checkbox\" name=\"vehicle\" value=\"Airplane\" />\n\nThen, use getlist() method in your view:\ndef delete(request):\n values = request.POST.getlist(u'vehicle')\n # Handling goes here.\n\nBut anyway, unless you really need to do custom stuff (however special cases are not special enough to break the rules ;), use Django forms. There already is a checkbox list OOTB. I'm not sure why do you even consider using JavaScript in this very case.\n",
"firstly, I don't know if you need to manipulate the checkbox values into a string like you are doing. if you allocate them the same name attribute, http (or jQuery's) serialisation will do it for you.\nOn the Django side use getlist to grab a list, the [] accessor only gets the last value in a list of params.\nHttp default handling however doesn't send through the values of checkboxes that aren't checked, so you might want to build in some checks that compare the checkboxes you build vs the data you get back.\nAs Gavoja says above, django forms is probably a good answer for this:\nSpecifically, you want to use MultipleChoiceField with a CheckboxSelectMultiple widget and the choices as your options:\n\nmy_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())\n\nalso see: In Django is there a way to display choices as checkboxes?\n"
] |
[
9,
2
] |
[] |
[] |
[
"django",
"jquery",
"python"
] |
stackoverflow_0002190998_django_jquery_python.txt
|
Q:
Using if-condition to check filename
I'm doing a real silly mistake in Python but unable to find what it is
I'm doing something like this in python
filename="file1"
if name == 'file1'
print 1
I'm getting an invalid syntax error
A:
You are missing a colon
filename="file1"
if name == 'file1':
print 1
A:
You need to put a colon at the end of the if statment
filename="file1"
if name == 'file1':
print 1
A:
what is name?? did you define it elsewhere?? I assume its "filename" instead, so
filename="file1"
if filename == 'file1':
print 1
if "name" is defined, then the problem is indeed the ":" at the end of "if" line.
|
Using if-condition to check filename
|
I'm doing a real silly mistake in Python but unable to find what it is
I'm doing something like this in python
filename="file1"
if name == 'file1'
print 1
I'm getting an invalid syntax error
|
[
"You are missing a colon\nfilename=\"file1\"\nif name == 'file1':\n print 1\n\n",
"You need to put a colon at the end of the if statment\nfilename=\"file1\"\nif name == 'file1':\n print 1\n\n",
"what is name?? did you define it elsewhere?? I assume its \"filename\" instead, so\nfilename=\"file1\"\nif filename == 'file1':\n print 1\n\nif \"name\" is defined, then the problem is indeed the \":\" at the end of \"if\" line.\n"
] |
[
7,
4,
1
] |
[] |
[] |
[
"python",
"syntax_error"
] |
stackoverflow_0002191262_python_syntax_error.txt
|
Q:
None in boost.python
I am trying to translate the following code
d = {}
d[0] = None
into C++ with boost.python
boost::python::dict d;
d[0] = ?None
How can I get a None object in boost.python?
A:
There is no constructor of boost::python::object that takes a PyObject* (from my understanding, a ctor like that would invalidate the whole idea if mapping Python types to C++ types anyway, because the PyObject* could be anything). According to the documentation:
object();
Effects: Constructs an object managing a reference to the Python None object.
A:
You could use:
d[0] = d.get(0)
d.get defaults to None if you don't specify a default value.
|
None in boost.python
|
I am trying to translate the following code
d = {}
d[0] = None
into C++ with boost.python
boost::python::dict d;
d[0] = ?None
How can I get a None object in boost.python?
|
[
"There is no constructor of boost::python::object that takes a PyObject* (from my understanding, a ctor like that would invalidate the whole idea if mapping Python types to C++ types anyway, because the PyObject* could be anything). According to the documentation:\n\nobject();\nEffects: Constructs an object managing a reference to the Python None object.\n\n",
"You could use:\nd[0] = d.get(0)\n\nd.get defaults to None if you don't specify a default value.\n"
] |
[
26,
3
] |
[] |
[] |
[
"boost",
"c++",
"python"
] |
stackoverflow_0002190349_boost_c++_python.txt
|
Q:
Python Creating Unwanted Folder in Directory
Python is creating a folder in my directory every time I call this method. The method is in one of my Django applications that requires access to the server's local area.
def filepath(filename, foldername='', envar='MYAPPDIR'):
if envar is not None and envar is os.environ:
dirpath = os.environ[envar]
else:
dirpath = '~/myFolder/%s' % foldername
expanded = os.path.expanduser(dirpath)
if not os.path.isdir(expanded):
if os.path.lexists(expanded):
raise IOError(errno.EEXIST, "Path is a file, nor a dir", expanded)
os.makedirs(expanded)
return os.path.join(expanded, filename)
I'd like to stop it from happening.
Please note: the user can specify if it's in another directory within the default. Therefore the default folder is myFolder, however if the user wants to use a folder called myOtherFolder within myFolder (therefore ~/myFolder/myOtherFolder/) then they can. This is the kind of functionality I'm trying to implement, hence my using folder='' if no argument is passed to the method(which I think is the problem).
A:
def filepath(filename, foldername=None, envar='MYAPPDIR'):
default = '~/myFolder'
if foldername:
default = os.path.join(default, foldername)
dirpath = os.path.expanduser(os.environ.get(envar, default))
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return os.path.join(dirpath, filename)
Biggest change removing the "is" typo you had in the first if's condition (did you mean "in"?).
However, it appears you want envar to override "~/myFolder", not "~/myFolder/otherSpecifiedByUser", giving:
def filepath(filename, foldername=None, envar='MYAPPDIR'):
dirpath = os.path.expanduser(os.environ.get(envar, "~/myFolder"))
if foldername:
dirpath = os.path.join(dirpath, foldername)
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return os.path.join(dirpath, filename)
Also, if you're storing config files, then you can trivially follow the XDG basedir spec, if you're really using something like "~/.myFolder":
def filepath(filename, foldername=None, envar='MYAPPDIR'):
default = os.path.join(os.environ.get("XDG_CONFIG_HOME", "~/.config"), "myFolder")
dirpath = os.path.expanduser(os.environ.get(envar, default))
if foldername:
dirpath = os.path.join(dirpath, foldername)
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return os.path.join(dirpath, filename)
A:
I guess it's going into the second part of your initial if clause. Can you print out the values of envar and the keys in os.environ when you run this in your environment? That should give you your answer. Also, you realise that os.environ is the environment in which your server is running and is not dependent on the anything from the client, don't you?
|
Python Creating Unwanted Folder in Directory
|
Python is creating a folder in my directory every time I call this method. The method is in one of my Django applications that requires access to the server's local area.
def filepath(filename, foldername='', envar='MYAPPDIR'):
if envar is not None and envar is os.environ:
dirpath = os.environ[envar]
else:
dirpath = '~/myFolder/%s' % foldername
expanded = os.path.expanduser(dirpath)
if not os.path.isdir(expanded):
if os.path.lexists(expanded):
raise IOError(errno.EEXIST, "Path is a file, nor a dir", expanded)
os.makedirs(expanded)
return os.path.join(expanded, filename)
I'd like to stop it from happening.
Please note: the user can specify if it's in another directory within the default. Therefore the default folder is myFolder, however if the user wants to use a folder called myOtherFolder within myFolder (therefore ~/myFolder/myOtherFolder/) then they can. This is the kind of functionality I'm trying to implement, hence my using folder='' if no argument is passed to the method(which I think is the problem).
|
[
"def filepath(filename, foldername=None, envar='MYAPPDIR'):\n default = '~/myFolder'\n if foldername:\n default = os.path.join(default, foldername)\n dirpath = os.path.expanduser(os.environ.get(envar, default))\n\n try:\n os.makedirs(dirpath)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n return os.path.join(dirpath, filename)\n\nBiggest change removing the \"is\" typo you had in the first if's condition (did you mean \"in\"?).\nHowever, it appears you want envar to override \"~/myFolder\", not \"~/myFolder/otherSpecifiedByUser\", giving:\ndef filepath(filename, foldername=None, envar='MYAPPDIR'):\n dirpath = os.path.expanduser(os.environ.get(envar, \"~/myFolder\"))\n if foldername:\n dirpath = os.path.join(dirpath, foldername)\n\n try:\n os.makedirs(dirpath)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n return os.path.join(dirpath, filename)\n\nAlso, if you're storing config files, then you can trivially follow the XDG basedir spec, if you're really using something like \"~/.myFolder\":\ndef filepath(filename, foldername=None, envar='MYAPPDIR'):\n default = os.path.join(os.environ.get(\"XDG_CONFIG_HOME\", \"~/.config\"), \"myFolder\")\n dirpath = os.path.expanduser(os.environ.get(envar, default))\n if foldername:\n dirpath = os.path.join(dirpath, foldername)\n\n try:\n os.makedirs(dirpath)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n return os.path.join(dirpath, filename)\n\n",
"I guess it's going into the second part of your initial if clause. Can you print out the values of envar and the keys in os.environ when you run this in your environment? That should give you your answer. Also, you realise that os.environ is the environment in which your server is running and is not dependent on the anything from the client, don't you?\n"
] |
[
3,
0
] |
[] |
[] |
[
"file_access",
"python"
] |
stackoverflow_0002191402_file_access_python.txt
|
Q:
How to match info from a string
I have a string which has a version number. I want to read the version number from this code so I can compare it with other code I am using. I have code done below but cannot get it working, can anyone see the problem?
print results
r = re.compile(r'(version\s*\s*)(\S+)')
for l in results:
m1 = r.match(l)
if m1:
ID=map(int,m1.group(2).split("."))
l = r.sub(r'\g<1>' + '.'.join(['%s' % (v) for v in ID]), l)
print ID
the results variable is:
Name Info Type Call version 1.0.40.437 Fri Oct 2 10:54:35 BST 2009
I have it done this way as I need the numbers in the ID separated into groups as I need to compare the 3rd number in the ID to the third number in the ID in another file.
The below answers are useful, but the way I had it would read a file and take all the numbers out and put them into a list so all I would have to do is compare the two numbers of the list. Sorry if the question was not clear but I don't want the version number to be a string.
Okay I made a couple of changes to the code that was answered below. The code is as follows:
version = re.compile('version\s+([\d.]+)\s+')
ID = version.search(results)
if ID:
value = ID.group(1).split('.')[2]
self.assertEqual(BUILD_ID[2], int(value))
This does not create the list that I wanted but it allows me to compare the 2 values.
Thanks for all the help.
A:
Why regexp? I should use split(' ') and use value next to 'version', or simplier:
print results.split(' ')[5]
If you must use regexp then try:
rx = re.compile('version\s+([\d.]+)\s+')
rxx = rx.search(results)
if rxx:
print rxx.group(1)
A:
here's a non regex way
>>> s="Name Info Type Call version 1.0.40.437 Fri Oct 2 10:54:35 BST 2009".split()
>>> for n,i in enumerate(s):
... if "version" in i:
... print s[n+1]
...
1.0.40.437
>>>
A:
>>> r = re.compile(r'version (\S*)')
>>> r.findall(results)
['1.0.40.437']
Non regexp way
>>> m=results.split()
>>> m[m.index('version')+1]
'1.0.40.437'
A:
>>> import re
>>> results = "Name Info Type Call version 1.0.40.437 Fri Oct 2 10:54:35 BST 2009"
>>> m = re.search("version ([^ ]+)", results)
>>> if m:
... version = m.group(1)
... print "matched, found:", version
... else:
... print "didn't find a version"
...
matched, found: 1.0.40.437
A:
I can spot a couple of things:
You say results is a string, but you're iterating through it - so l is a character each time.
re.match only matches at the beginning of a string. Use re.search instead.
A:
The below answers are useful, but the way I had it would read a file and take all the numbers out and put them into a list so all I would have to do is compare the two numbers of the list.
I'm going to assume that the version format is fixed (ie. version.major.minor.revision).
reVersion = re.compile( 'version\s+((((\d+)\.(\d+))\.(\d+)).(\S+))\s+', re.I )
for result in results:
versionMatch = reVersion.match( result )
if versionMatch:
version = versionMatch.groups()
print( version[0] ) # 1.0.40.437 full version
print( version[1] ) # 1.0.40 version.major.minor - no revision
print( version[2] ) # 1.0 version.major
print( version[3] ) # 1 version
print( version[4] ) # 0 major
print( version[5] ) # 40 minor
print( version[6] ) # 437 revision
|
How to match info from a string
|
I have a string which has a version number. I want to read the version number from this code so I can compare it with other code I am using. I have code done below but cannot get it working, can anyone see the problem?
print results
r = re.compile(r'(version\s*\s*)(\S+)')
for l in results:
m1 = r.match(l)
if m1:
ID=map(int,m1.group(2).split("."))
l = r.sub(r'\g<1>' + '.'.join(['%s' % (v) for v in ID]), l)
print ID
the results variable is:
Name Info Type Call version 1.0.40.437 Fri Oct 2 10:54:35 BST 2009
I have it done this way as I need the numbers in the ID separated into groups as I need to compare the 3rd number in the ID to the third number in the ID in another file.
The below answers are useful, but the way I had it would read a file and take all the numbers out and put them into a list so all I would have to do is compare the two numbers of the list. Sorry if the question was not clear but I don't want the version number to be a string.
Okay I made a couple of changes to the code that was answered below. The code is as follows:
version = re.compile('version\s+([\d.]+)\s+')
ID = version.search(results)
if ID:
value = ID.group(1).split('.')[2]
self.assertEqual(BUILD_ID[2], int(value))
This does not create the list that I wanted but it allows me to compare the 2 values.
Thanks for all the help.
|
[
"Why regexp? I should use split(' ') and use value next to 'version', or simplier:\nprint results.split(' ')[5]\n\nIf you must use regexp then try:\nrx = re.compile('version\\s+([\\d.]+)\\s+')\nrxx = rx.search(results)\nif rxx:\n print rxx.group(1)\n\n",
"here's a non regex way\n>>> s=\"Name Info Type Call version 1.0.40.437 Fri Oct 2 10:54:35 BST 2009\".split()\n>>> for n,i in enumerate(s):\n... if \"version\" in i:\n... print s[n+1]\n...\n1.0.40.437\n>>>\n\n",
">>> r = re.compile(r'version (\\S*)')\n>>> r.findall(results)\n['1.0.40.437']\n\nNon regexp way\n>>> m=results.split()\n>>> m[m.index('version')+1]\n'1.0.40.437'\n\n",
">>> import re\n>>> results = \"Name Info Type Call version 1.0.40.437 Fri Oct 2 10:54:35 BST 2009\"\n>>> m = re.search(\"version ([^ ]+)\", results)\n>>> if m:\n... version = m.group(1)\n... print \"matched, found:\", version\n... else:\n... print \"didn't find a version\"\n... \nmatched, found: 1.0.40.437\n\n",
"I can spot a couple of things:\n\nYou say results is a string, but you're iterating through it - so l is a character each time.\nre.match only matches at the beginning of a string. Use re.search instead.\n\n",
"\n\nThe below answers are useful, but the way I had it would read a file and take all the numbers out and put them into a list so all I would have to do is compare the two numbers of the list.\n\n\nI'm going to assume that the version format is fixed (ie. version.major.minor.revision).\nreVersion = re.compile( 'version\\s+((((\\d+)\\.(\\d+))\\.(\\d+)).(\\S+))\\s+', re.I )\n\nfor result in results:\n versionMatch = reVersion.match( result )\n if versionMatch:\n version = versionMatch.groups()\n print( version[0] ) # 1.0.40.437 full version\n print( version[1] ) # 1.0.40 version.major.minor - no revision\n print( version[2] ) # 1.0 version.major\n print( version[3] ) # 1 version\n print( version[4] ) # 0 major\n print( version[5] ) # 40 minor\n print( version[6] ) # 437 revision\n\n"
] |
[
3,
2,
2,
0,
0,
0
] |
[] |
[] |
[
"python",
"search",
"string"
] |
stackoverflow_0002191202_python_search_string.txt
|
Q:
How can I load test data into AppEngine automatically?
I'd like to automatically load some test data into the AppEngine datastore when a local copy is run by one of my team's developers. I know that the bulk uploader lets you do this from the command line, but I'm looking for something automatic. Inevitably we will forget to load data when we clear our test copies of the datastore.
Currently I'm just checking for a known entity when the main page is loaded, and calling a function to insert the data when that entity isn't found. This seems wasteful--it gets called every time anybody hits this particular page.
The ideal solution would be something that won't affect the deployed version of the app at appspot.com and won't add messy code to a central code path.
A:
Why not just automate the bulk loader? It's a command line tool, as you point out, so trivial to run from your build process (or whatever other trigger you want).
|
How can I load test data into AppEngine automatically?
|
I'd like to automatically load some test data into the AppEngine datastore when a local copy is run by one of my team's developers. I know that the bulk uploader lets you do this from the command line, but I'm looking for something automatic. Inevitably we will forget to load data when we clear our test copies of the datastore.
Currently I'm just checking for a known entity when the main page is loaded, and calling a function to insert the data when that entity isn't found. This seems wasteful--it gets called every time anybody hits this particular page.
The ideal solution would be something that won't affect the deployed version of the app at appspot.com and won't add messy code to a central code path.
|
[
"Why not just automate the bulk loader? It's a command line tool, as you point out, so trivial to run from your build process (or whatever other trigger you want).\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"python",
"web_applications"
] |
stackoverflow_0002190622_google_app_engine_python_web_applications.txt
|
Q:
Python: feedback / corrections on first OOP style script
I would like some feedback on my first Python script that makes use of OOP style. This is a Munin plugin that graphs average fan speed or average chassis temp depending on the name of the plugin (dell_fans, dell_temps).
An hour or so ago I submitted a procedural version of the fan speed plugin to stackoverflow to get help converting it to an OOP style. I then built off of that to combine the two scripts. Any feedback, suggestions, corrections would be very helpful. I would like to correct any misconceptions I may have before they cement.
Update: Modified to have common base class. Any other suggestions?
import sys
import subprocess
class Statistics(object):
def __init__(self, command):
self.command = command.split()
def average(self):
data = subprocess.Popen(self.command,stdout=subprocess.PIPE).stdout.readlines()
count = total = 0
for item in data:
if "Reading" in item:
# Extract variable length fan speed, without regex.
total += float(item.split(":")[1].split()[0])
count += 1
# Sometimes omreport returns zero output if omsa services aren't started.
if not count or not total:
raise ValueError("No output from omreport. Is OMSA services started?")
avg = (total / count)
return avg
def print_autoconfig(self):
print "autoconfig goes here"
class Fanspeed(Statistics):
def __init__(self, command):
Statistics.__init__(self, command)
def print_config(self):
print "graph_title Average Fan Speed"
print "graph_args --base 1000 -l 0"
print "graph_vlabel speed (RPM)"
print "graph_category Chassis"
print "graph_info This graph shows the average speed of all fans"
print "graph_period second"
print "data.label speed"
print "data.info Average fan speed for the five minutes."
class Temps(Statistics):
def __init__(self, command):
Statistics.__init__(self, command)
def print_config(self):
print "graph_title Average Temperature"
print "graph_args --upper-limit 120 -l 0"
print "graph_vlabel Celsius"
print "graph_category Chassis"
print "graph_info This graph shows the avg temp of all sensors."
print "graph_period second"
print "data.label temp"
print "data.info Average chassis temperature for the five minutes."
if __name__ == '__main__':
# Munin populates sys.argv[1] with "" (an empty argument), lets remove it.
sys.argv = [x for x in sys.argv if x]
if "fans" in sys.argv[0]:
cmd = "/usr/sbin/omreport chassis fans"
omdata = Fanspeed(cmd)
elif "temps" in sys.argv[0]:
cmd = "/usr/sbin/omreport chassis temps"
omdata = Temps(cmd)
else:
print >> sys.stderr, "Change filename to dell_fans or dell_temps."
sys.exit(1)
if len(sys.argv) > 1:
if sys.argv[1].lower() == "autoconfig":
omdata.print_autoconfig()
elif sys.argv[1].lower() == "config":
omdata.print_config()
else:
try:
average = omdata.average()
print "data.value %s" % average
except OSError, e:
print >> sys.stderr, "Error running '%s', %s" % (cmd, e)
sys.exit(1)
except ValueError, e:
# Sometimes omreport returns zero output if omsa services aren't started.
print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.'
print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".'
sys.exit(1)
A:
Is Temps a FanSpeed? That's the litmus test for whether subclassing is appropriate (e.g. an elephant is an animal, a car is not an animal - so it might be appropriate to have a subclass of Animal which models an elephant, but not a subclass of Animal which models a car).
It sounds like they're modelling two different things - so yes, create a common base class for them.
A:
A sematically more appropriate way would be to define one main class (for example, FanStatistics or whatever you want to call it), in which you define general methods, like the average method, and the subclass it into FanSpeed and FanTemp. That way you wouldn't confuse the names, as the temperature is not a subclass, or specialization, of the speed – but the speed and the temperature are both specializations of the abstract statistics data.
A:
It sounds to me like you have two different kinds of statistics that you want to model, fan speed (Fanspeed) and temperatute (Temps). If there is some common functionality that you want share between them create common base class for them lets call it Statistic for example.
class Statistic(object):
def average(self):
pass # your logic to calculate the average here
class Fanspeed(Statistic):
pass # your fan speed functionaly here
class Temps(Statistic):
pass # your temperature functionaly here
|
Python: feedback / corrections on first OOP style script
|
I would like some feedback on my first Python script that makes use of OOP style. This is a Munin plugin that graphs average fan speed or average chassis temp depending on the name of the plugin (dell_fans, dell_temps).
An hour or so ago I submitted a procedural version of the fan speed plugin to stackoverflow to get help converting it to an OOP style. I then built off of that to combine the two scripts. Any feedback, suggestions, corrections would be very helpful. I would like to correct any misconceptions I may have before they cement.
Update: Modified to have common base class. Any other suggestions?
import sys
import subprocess
class Statistics(object):
def __init__(self, command):
self.command = command.split()
def average(self):
data = subprocess.Popen(self.command,stdout=subprocess.PIPE).stdout.readlines()
count = total = 0
for item in data:
if "Reading" in item:
# Extract variable length fan speed, without regex.
total += float(item.split(":")[1].split()[0])
count += 1
# Sometimes omreport returns zero output if omsa services aren't started.
if not count or not total:
raise ValueError("No output from omreport. Is OMSA services started?")
avg = (total / count)
return avg
def print_autoconfig(self):
print "autoconfig goes here"
class Fanspeed(Statistics):
def __init__(self, command):
Statistics.__init__(self, command)
def print_config(self):
print "graph_title Average Fan Speed"
print "graph_args --base 1000 -l 0"
print "graph_vlabel speed (RPM)"
print "graph_category Chassis"
print "graph_info This graph shows the average speed of all fans"
print "graph_period second"
print "data.label speed"
print "data.info Average fan speed for the five minutes."
class Temps(Statistics):
def __init__(self, command):
Statistics.__init__(self, command)
def print_config(self):
print "graph_title Average Temperature"
print "graph_args --upper-limit 120 -l 0"
print "graph_vlabel Celsius"
print "graph_category Chassis"
print "graph_info This graph shows the avg temp of all sensors."
print "graph_period second"
print "data.label temp"
print "data.info Average chassis temperature for the five minutes."
if __name__ == '__main__':
# Munin populates sys.argv[1] with "" (an empty argument), lets remove it.
sys.argv = [x for x in sys.argv if x]
if "fans" in sys.argv[0]:
cmd = "/usr/sbin/omreport chassis fans"
omdata = Fanspeed(cmd)
elif "temps" in sys.argv[0]:
cmd = "/usr/sbin/omreport chassis temps"
omdata = Temps(cmd)
else:
print >> sys.stderr, "Change filename to dell_fans or dell_temps."
sys.exit(1)
if len(sys.argv) > 1:
if sys.argv[1].lower() == "autoconfig":
omdata.print_autoconfig()
elif sys.argv[1].lower() == "config":
omdata.print_config()
else:
try:
average = omdata.average()
print "data.value %s" % average
except OSError, e:
print >> sys.stderr, "Error running '%s', %s" % (cmd, e)
sys.exit(1)
except ValueError, e:
# Sometimes omreport returns zero output if omsa services aren't started.
print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.'
print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".'
sys.exit(1)
|
[
"Is Temps a FanSpeed? That's the litmus test for whether subclassing is appropriate (e.g. an elephant is an animal, a car is not an animal - so it might be appropriate to have a subclass of Animal which models an elephant, but not a subclass of Animal which models a car).\nIt sounds like they're modelling two different things - so yes, create a common base class for them.\n",
"A sematically more appropriate way would be to define one main class (for example, FanStatistics or whatever you want to call it), in which you define general methods, like the average method, and the subclass it into FanSpeed and FanTemp. That way you wouldn't confuse the names, as the temperature is not a subclass, or specialization, of the speed – but the speed and the temperature are both specializations of the abstract statistics data.\n",
"It sounds to me like you have two different kinds of statistics that you want to model, fan speed (Fanspeed) and temperatute (Temps). If there is some common functionality that you want share between them create common base class for them lets call it Statistic for example.\nclass Statistic(object):\n def average(self):\n pass # your logic to calculate the average here\n\nclass Fanspeed(Statistic):\n pass # your fan speed functionaly here\n\nclass Temps(Statistic):\n pass # your temperature functionaly here\n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0002191639_oop_python.txt
|
Q:
Verify if provided string corresponds to pattern on python
could you please advice how to verify in python if provided string correspond to provided pattern and return result.
For example the provided pattern is following:
< [prefix]-[id]> separated by ','>|< log >"
where prefix is any number of alphabetic characters,
id is only numbers but not exceeding 5 digits,
log is any number of any characters
examples:
proj-123|log message
proj-234, proj-345|log message
I suppose the easiest way is to apply regexp which I didn't use on python.
Thanks.
A:
(?:[a-z]+-\d{1,5})(?:, [a-z]+-\d{1,5})*\|.*
it's not clear what you want to capture, that's why I use non-capturing groups. If you need only boolean:
>>> regex = '[a-z]+-\d{1,5}(?:, [a-z]+-\d{1,5})*\|.*'
>>> re.match(regex, 'proj-234, proj-345|log message') is not None
True
Of course, the same result can be achieved with the sequence of simple string methods:
prefs, _, log = subj.partition('|')
for group in prefs.split(', '):
pref, _, id5 = group.partition('-')
if id5.isdigit() and len(id5) <= 5 and pref.isalpha():
print(pref, id5)
A:
Python has great regexp library in stdlib. Here is documentation. Simply use re.match and that should be all you need.
A:
Extending SilentGhosts' excellent regexp...
The following will match more than two comma separated tags and it captures the tags in one group and the log message in another group:
import re
line = 'proj-234,proj-345,proj-543|log message'
match = re.match('((?:[a-zA-Z]+-\d{1,5})(?:,[a-zA-Z]+-\d{1,5})+)\|(.*)', line)
tags = match.group(1).split(',')
log_msg = match.group(2)
I wasn't able to figure out if it was possible to capture the tags following the first tag without capturing the comma, so I decided to capture them in one group and split them after the fact.
|
Verify if provided string corresponds to pattern on python
|
could you please advice how to verify in python if provided string correspond to provided pattern and return result.
For example the provided pattern is following:
< [prefix]-[id]> separated by ','>|< log >"
where prefix is any number of alphabetic characters,
id is only numbers but not exceeding 5 digits,
log is any number of any characters
examples:
proj-123|log message
proj-234, proj-345|log message
I suppose the easiest way is to apply regexp which I didn't use on python.
Thanks.
|
[
"(?:[a-z]+-\\d{1,5})(?:, [a-z]+-\\d{1,5})*\\|.*\n\nit's not clear what you want to capture, that's why I use non-capturing groups. If you need only boolean:\n>>> regex = '[a-z]+-\\d{1,5}(?:, [a-z]+-\\d{1,5})*\\|.*'\n>>> re.match(regex, 'proj-234, proj-345|log message') is not None\nTrue\n\nOf course, the same result can be achieved with the sequence of simple string methods:\nprefs, _, log = subj.partition('|')\nfor group in prefs.split(', '):\n pref, _, id5 = group.partition('-')\n if id5.isdigit() and len(id5) <= 5 and pref.isalpha():\n print(pref, id5)\n\n",
"Python has great regexp library in stdlib. Here is documentation. Simply use re.match and that should be all you need.\n",
"Extending SilentGhosts' excellent regexp...\nThe following will match more than two comma separated tags and it captures the tags in one group and the log message in another group:\nimport re\n\nline = 'proj-234,proj-345,proj-543|log message'\nmatch = re.match('((?:[a-zA-Z]+-\\d{1,5})(?:,[a-zA-Z]+-\\d{1,5})+)\\|(.*)', line)\ntags = match.group(1).split(',')\nlog_msg = match.group(2)\n\nI wasn't able to figure out if it was possible to capture the tags following the first tag without capturing the comma, so I decided to capture them in one group and split them after the fact.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python",
"regex",
"string"
] |
stackoverflow_0002191581_python_regex_string.txt
|
Q:
How to get a reference to the current class from class body?
I want to keep a dictionary of (all, non-immediate included) subclasses in a base class, so that I can instantiate them from a string. I'm doing this because the CLSID is sent through a web form, so I want to restrict the choices to the ones set from the subclasses. (I don't want to eval()/globals() the classname).
class BaseClass(object):
CLSID = 'base'
CLASSES = {}
def from_string(str):
return CLASSES[str]()
class Foo(BaseClass):
CLSID = 'foo'
BaseClass.CLASSES[CLSID] = Foo
class Bar(BaseClass):
CLSID = 'bar'
BaseClass.CLASSES[CLSID] = Bar
That obviously doesnt work. But is there something like a @classmethod for init? The idea is that this classmethod would only run once as each class is read and register the class with the baseclass. Something like the following could then work: (Would also save the extra line in Foo and Bar)
class BaseClass(object):
CLSID = 'base'
CLASSES = {}
@classmethod
def __init__(cls):
BaseClass.CLASSES[cls.CLSID] = cls
def from_string(str):
return CLASSES[str]()
I thought about using __subclasses__ and then filter() on CLSID, but that only works for immediate subclasses.
So, hoping that I explained my purpose, the question is how to make this work? Or am I going about this in a completely wrong way?
A:
Irrevocably tying this with the base class:
class AutoRegister(type):
def __new__(mcs, name, bases, D):
self = type.__new__(mcs, name, bases, D)
if "ID" in D: # only register if has ID attribute directly
if self.ID in self._by_id:
raise ValueError("duplicate ID: %r" % self.ID)
self._by_id[self.ID] = self
return self
class Base(object):
__metaclass__ = AutoRegister
_by_id = {}
ID = "base"
@classmethod
def from_id(cls, id):
return cls._by_id[id]()
class A(Base):
ID = "A"
class B(Base):
ID = "B"
print Base.from_id("A")
print Base.from_id("B")
Or keeping disparate concerns actually separate:
class IDFactory(object):
def __init__(self):
self._by_id = {}
def register(self, cls):
self._by_id[cls.ID] = cls
return cls
def __call__(self, id, *args, **kwds):
return self._by_id[id](*args, **kwds)
# could use a from_id function instead, as above
factory = IDFactory()
@factory.register
class Base(object):
ID = "base"
@factory.register
class A(Base):
ID = "A"
@factory.register
class B(Base):
ID = "B"
print factory("A")
print factory("B")
You may have picked up on which one I prefer. Defined separately from the class hierarchy, you can easily extend and modify, such as by registering under two names (using an ID attribute only allows one):
class IDFactory(object):
def __init__(self):
self._by_id = {}
def register(self, cls):
self._by_id[cls.ID] = cls
return cls
def register_as(self, name):
def wrapper(cls):
self._by_id[name] = cls
return cls
return wrapper
# ...
@factory.register_as("A") # doesn't require ID anymore
@factory.register # can still use ID, even mix and match
@factory.register_as("B") # imagine we got rid of B,
class A(object): # and A fulfills that roll now
ID = "A"
You can also keep the factory instance "inside" the base while keeping it decoupled:
class IDFactory(object):
#...
class Base(object):
factory = IDFactory()
@classmethod
def register(cls, subclass):
if subclass.ID in cls.factory:
raise ValueError("duplicate ID: %r" % subclass.ID)
cls.factory[subclass.ID] = subclass
return subclass
@Base.factory.register # still completely decoupled
# (it's an attribute of Base, but that can be easily
# changed without modifying the class A below)
@Base.register # alternatively more coupled, but possibly desired
class A(Base):
ID = "A"
A:
You could muck with metaclasses to do the job for you, but I think a simpler solution might suffice:
class BaseClass(object):
CLASS_ID = None
_CLASSES = {}
@classmethod
def create_from_id(cls, class_id):
return CLASSES[class_id]()
@classmethod
def register(cls):
assert cls.CLASS_ID is not None, "subclass %s must define a CLASS_ID" % cls
cls._CLASSES[cls.CLASS_ID] = cls
Then to define a subclass just use:
class Foo(BaseClass):
CLASS_ID = 'foo'
Foo.register()
And finally use the factory method in the BaseClass to create the instances for you:
foo = BaseClass.create_from_id('foo')
In this solution, after the class definition you must call the register class method to register the subclass into the base class. Also, the default CLASS_ID is None to avoid overwriting the base class in the registry if a user forgets to define it.
|
How to get a reference to the current class from class body?
|
I want to keep a dictionary of (all, non-immediate included) subclasses in a base class, so that I can instantiate them from a string. I'm doing this because the CLSID is sent through a web form, so I want to restrict the choices to the ones set from the subclasses. (I don't want to eval()/globals() the classname).
class BaseClass(object):
CLSID = 'base'
CLASSES = {}
def from_string(str):
return CLASSES[str]()
class Foo(BaseClass):
CLSID = 'foo'
BaseClass.CLASSES[CLSID] = Foo
class Bar(BaseClass):
CLSID = 'bar'
BaseClass.CLASSES[CLSID] = Bar
That obviously doesnt work. But is there something like a @classmethod for init? The idea is that this classmethod would only run once as each class is read and register the class with the baseclass. Something like the following could then work: (Would also save the extra line in Foo and Bar)
class BaseClass(object):
CLSID = 'base'
CLASSES = {}
@classmethod
def __init__(cls):
BaseClass.CLASSES[cls.CLSID] = cls
def from_string(str):
return CLASSES[str]()
I thought about using __subclasses__ and then filter() on CLSID, but that only works for immediate subclasses.
So, hoping that I explained my purpose, the question is how to make this work? Or am I going about this in a completely wrong way?
|
[
"Irrevocably tying this with the base class:\nclass AutoRegister(type):\n def __new__(mcs, name, bases, D):\n self = type.__new__(mcs, name, bases, D)\n if \"ID\" in D: # only register if has ID attribute directly\n if self.ID in self._by_id:\n raise ValueError(\"duplicate ID: %r\" % self.ID)\n self._by_id[self.ID] = self\n return self\n\nclass Base(object):\n __metaclass__ = AutoRegister\n _by_id = {}\n ID = \"base\"\n\n @classmethod\n def from_id(cls, id):\n return cls._by_id[id]()\n\nclass A(Base):\n ID = \"A\"\n\nclass B(Base):\n ID = \"B\"\n\nprint Base.from_id(\"A\")\nprint Base.from_id(\"B\")\n\nOr keeping disparate concerns actually separate:\nclass IDFactory(object):\n def __init__(self):\n self._by_id = {}\n def register(self, cls):\n self._by_id[cls.ID] = cls\n return cls\n\n def __call__(self, id, *args, **kwds):\n return self._by_id[id](*args, **kwds)\n # could use a from_id function instead, as above\n\nfactory = IDFactory()\n\n@factory.register\nclass Base(object):\n ID = \"base\"\n\n@factory.register\nclass A(Base):\n ID = \"A\"\n\n@factory.register\nclass B(Base):\n ID = \"B\"\n\nprint factory(\"A\")\nprint factory(\"B\")\n\nYou may have picked up on which one I prefer. Defined separately from the class hierarchy, you can easily extend and modify, such as by registering under two names (using an ID attribute only allows one):\nclass IDFactory(object):\n def __init__(self):\n self._by_id = {}\n\n def register(self, cls):\n self._by_id[cls.ID] = cls\n return cls\n\n def register_as(self, name):\n def wrapper(cls):\n self._by_id[name] = cls\n return cls\n return wrapper\n\n # ...\n\n@factory.register_as(\"A\") # doesn't require ID anymore\n@factory.register # can still use ID, even mix and match\n@factory.register_as(\"B\") # imagine we got rid of B,\nclass A(object): # and A fulfills that roll now\n ID = \"A\"\n\nYou can also keep the factory instance \"inside\" the base while keeping it decoupled:\nclass IDFactory(object):\n #...\n\nclass Base(object):\n factory = IDFactory()\n\n @classmethod\n def register(cls, subclass):\n if subclass.ID in cls.factory:\n raise ValueError(\"duplicate ID: %r\" % subclass.ID)\n cls.factory[subclass.ID] = subclass\n return subclass\n\n@Base.factory.register # still completely decoupled\n # (it's an attribute of Base, but that can be easily\n # changed without modifying the class A below)\n@Base.register # alternatively more coupled, but possibly desired\nclass A(Base):\n ID = \"A\"\n\n",
"You could muck with metaclasses to do the job for you, but I think a simpler solution might suffice:\nclass BaseClass(object):\n CLASS_ID = None\n _CLASSES = {}\n\n @classmethod\n def create_from_id(cls, class_id):\n return CLASSES[class_id]()\n\n @classmethod\n def register(cls):\n assert cls.CLASS_ID is not None, \"subclass %s must define a CLASS_ID\" % cls\n cls._CLASSES[cls.CLASS_ID] = cls\n\nThen to define a subclass just use:\nclass Foo(BaseClass):\n CLASS_ID = 'foo'\n\nFoo.register()\n\nAnd finally use the factory method in the BaseClass to create the instances for you:\nfoo = BaseClass.create_from_id('foo')\n\nIn this solution, after the class definition you must call the register class method to register the subclass into the base class. Also, the default CLASS_ID is None to avoid overwriting the base class in the registry if a user forgets to define it.\n"
] |
[
7,
3
] |
[] |
[] |
[
"class",
"inheritance",
"python"
] |
stackoverflow_0002191505_class_inheritance_python.txt
|
Q:
Conditional operator in Python?
do you know if Python supports some keyword or expression like in C++ to return values based on if condition, all in the same line (The C++ if expressed with the question mark ?)
// C++
value = ( a > 10 ? b : c )
A:
value = b if a > 10 else c
For Python 2.4 and lower you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:
value = [c, b][a > 10]
There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.
A:
simple is the best and works in every version.
if a>10:
value="b"
else:
value="c"
|
Conditional operator in Python?
|
do you know if Python supports some keyword or expression like in C++ to return values based on if condition, all in the same line (The C++ if expressed with the question mark ?)
// C++
value = ( a > 10 ? b : c )
|
[
"value = b if a > 10 else c\n\nFor Python 2.4 and lower you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:\nvalue = [c, b][a > 10]\n\nThere's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.\n",
"simple is the best and works in every version.\nif a>10: \n value=\"b\"\nelse: \n value=\"c\"\n\n"
] |
[
192,
1
] |
[] |
[] |
[
"python",
"syntax"
] |
stackoverflow_0002191890_python_syntax.txt
|
Q:
jquery autocomplete tagging
Can any one tell me how to use tagging auto-complete in django templates?
I have done this in django admin interface but i am confused to how to do it in the template.
Thanks in advance
A:
In my template i have this code:
$(document).ready(function(){
$("#tags1").autocomplete("/taglookup/", {
width: 320,
multiple: true,
multipleSeparator: " "
});
}
and on my url.py i have this on the urlparttern tuple, it can be anything depending on how you want to wire you views and urls!
(r'^taglookup/$', 'twine.twineapp.views.tag_lookup')
and on my views.py i have the tag_lookup view implemented as:
def tag_lookup(request):
# Default return list
results = []
if request.method == "GET":
if request.GET.has_key(u'q'):
value = request.GET[u'q']
# Ignore queries shorter than length 2
if len(value) > 2:
TI = Tag.objects.filter(name__startswith=value.lower())
results = [ x.name for x in TI]
return HttpResponse('\n'.join(results), mimetype='text/plain')
PS: Am using the Tagging package, that's why i have the Tag object in the above code.
A:
You could use my django-tagging-autocomplete reusable app and take advantage of provided TagAutocomplete form widget. You can find out more about using the widget in the documentation under "Using the form widget".
Please note that the app requires you use django-tagging for your tags. You also need to put {{ form.media }} (where "form" is the name of your form) inside the <head> section in your template, to allow the widget to include it's JavaScript files.
A:
This is from a template where I implemented autocomplete
$(document).ready(function() {
$("#searchbox").autocomplete('/search_stuff/', {
width: 300,
multiple: false,
matchContains: true,
delay: 900,
extraParams: {
s: function() { return $("#status").val(); }
}
});
Where search_stuff return a text list of all the items that fitted the criteria. Does that help?
|
jquery autocomplete tagging
|
Can any one tell me how to use tagging auto-complete in django templates?
I have done this in django admin interface but i am confused to how to do it in the template.
Thanks in advance
|
[
"In my template i have this code:\n$(document).ready(function(){\n $(\"#tags1\").autocomplete(\"/taglookup/\", {\n width: 320,\n multiple: true,\n multipleSeparator: \" \"\n });\n }\n\nand on my url.py i have this on the urlparttern tuple, it can be anything depending on how you want to wire you views and urls!\n(r'^taglookup/$', 'twine.twineapp.views.tag_lookup')\n\nand on my views.py i have the tag_lookup view implemented as:\ndef tag_lookup(request):\n # Default return list\n results = []\n if request.method == \"GET\":\n if request.GET.has_key(u'q'):\n value = request.GET[u'q']\n # Ignore queries shorter than length 2\n if len(value) > 2:\n TI = Tag.objects.filter(name__startswith=value.lower())\n results = [ x.name for x in TI]\n return HttpResponse('\\n'.join(results), mimetype='text/plain')\n\nPS: Am using the Tagging package, that's why i have the Tag object in the above code.\n",
"You could use my django-tagging-autocomplete reusable app and take advantage of provided TagAutocomplete form widget. You can find out more about using the widget in the documentation under \"Using the form widget\".\nPlease note that the app requires you use django-tagging for your tags. You also need to put {{ form.media }} (where \"form\" is the name of your form) inside the <head> section in your template, to allow the widget to include it's JavaScript files.\n",
"This is from a template where I implemented autocomplete\n$(document).ready(function() {\n\n $(\"#searchbox\").autocomplete('/search_stuff/', {\n width: 300,\n multiple: false,\n matchContains: true,\n delay: 900,\n extraParams: {\n s: function() { return $(\"#status\").val(); }\n }\n});\n\nWhere search_stuff return a text list of all the items that fitted the criteria. Does that help?\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"django",
"jquery",
"python"
] |
stackoverflow_0002191116_django_jquery_python.txt
|
Q:
Using Jython with Django?
I am planning to use Jython with Django. I want to know how stable the Jython project is, how easy to use it is, and how large its developer community is.
A:
Django is proven to work with Jython:
Special focus in Jython 2.5 was to make it compatible with modern web frameworks like Django
There is also a special project, django-jython, that focuses on making database backends and extensions available for Jython development.
There is explicit documentation on how to run Django on Jython
In theory, Jython is 100% compatible with CPython. In practice, some extensions or libraries may have badly written code that make them dependent on a specific Python implementation such as CPython. The django-jython project explicitly provides a tested solution to overcome this problem. Of course you can still run across some libraries that explicitly require CPython (hence mostly safe).
A:
I have not used Django with Jython, so I can't speak to that specific issue, but I've used Jython for other things and I've found it quite stable of late, and just as easy as plain Python. I believe the "core committers" in Jython are substantially fewer than in C-Python (maybe 1/3 the number or less), if that's what you mean by "developer community", but I'm not quite sure what's the point in asking about this -- are you considering joining either developer community (Jython or Core Python) and wondering where you could have the best impact?
If that's the case, I think the key issue isn't really how many others are already helping out, but, "what do you bring to the party" -- if you're a JVM wizard, or an expert at any important Java framework, you could be a real boon to the Jython community while that same skill would help much less in the C-Python community; vice versa, if you're a wizard, say, with autoconfigure and C-coded system calls, that would be precious for the C-Python community, but not as useful for the Jython community.
A:
I use Jython in testing and rapid-development.
From my point of view it is stable.
|
Using Jython with Django?
|
I am planning to use Jython with Django. I want to know how stable the Jython project is, how easy to use it is, and how large its developer community is.
|
[
"Django is proven to work with Jython:\n\nSpecial focus in Jython 2.5 was to make it compatible with modern web frameworks like Django\nThere is also a special project, django-jython, that focuses on making database backends and extensions available for Jython development.\nThere is explicit documentation on how to run Django on Jython\n\nIn theory, Jython is 100% compatible with CPython. In practice, some extensions or libraries may have badly written code that make them dependent on a specific Python implementation such as CPython. The django-jython project explicitly provides a tested solution to overcome this problem. Of course you can still run across some libraries that explicitly require CPython (hence mostly safe).\n",
"I have not used Django with Jython, so I can't speak to that specific issue, but I've used Jython for other things and I've found it quite stable of late, and just as easy as plain Python. I believe the \"core committers\" in Jython are substantially fewer than in C-Python (maybe 1/3 the number or less), if that's what you mean by \"developer community\", but I'm not quite sure what's the point in asking about this -- are you considering joining either developer community (Jython or Core Python) and wondering where you could have the best impact?\nIf that's the case, I think the key issue isn't really how many others are already helping out, but, \"what do you bring to the party\" -- if you're a JVM wizard, or an expert at any important Java framework, you could be a real boon to the Jython community while that same skill would help much less in the C-Python community; vice versa, if you're a wizard, say, with autoconfigure and C-coded system calls, that would be precious for the C-Python community, but not as useful for the Jython community.\n",
"I use Jython in testing and rapid-development. \nFrom my point of view it is stable.\n"
] |
[
5,
3,
2
] |
[] |
[] |
[
"jython",
"python"
] |
stackoverflow_0002179395_jython_python.txt
|
Q:
Python: convert RTF file to unicode?
I'm trying to convert lines in an RTF file to a series of unicode strings, and then do a regex match on the lines. (I need them to be unicode so that I can output them to another file.)
However, my regex match isn't working - I think because they aren't being converted into unicode properly.
Here's my code:
usefulLines = []
textData = {}
# the regex pattern for an entry in the db (e.g. SUF 76,22): it's sufficient for us to match on three upper-case characters plus a space
entryPattern = '^([A-Z]{3})[\s].*$'
f = open('textbase_1a.rtf', 'Ur')
fileLines = f.readlines()
# get the matching line numbers, and store in usefulLines
for i, line in enumerate(fileLines):
#line = line.decode('utf-16be') # this causes an error: I don't really know what file encoding the RTF file is in...
line = line.decode('mac_roman')
print line
if re.match(entryPattern, line):
# now retrieve the following lines, all the way up until we get a blank line
print "match: " + str(i)
usefulLines.append(i)
At the moment, this prints all the lines, but doesn't print anything with match - though it should match. Also, the lines are being printed with '/par' at the start, for some reason. When I try printing them to an output file, they look very strange.
Part of the problem is that I don't know what encoding to specify. How can I find this out?
If I use entryPattern = '^.*$' then I do get matches.
Can anyone help?
A:
You did not even decode the RTF file. RTFs are not just simple text files. A file containing "äöü", for example, contains this:
{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fswiss\fcharset0 Arial;}}
{*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20\'e4\'f6\'fc\par
}
when opened in a text editor. So the characters "äöü" are encoded as windows-1252 as declared at the beginning of the file (äöü = 0xE4 0xF6 0xFC).
For reading RTF you'll first need something that converts RTF to text (already asked here).
|
Python: convert RTF file to unicode?
|
I'm trying to convert lines in an RTF file to a series of unicode strings, and then do a regex match on the lines. (I need them to be unicode so that I can output them to another file.)
However, my regex match isn't working - I think because they aren't being converted into unicode properly.
Here's my code:
usefulLines = []
textData = {}
# the regex pattern for an entry in the db (e.g. SUF 76,22): it's sufficient for us to match on three upper-case characters plus a space
entryPattern = '^([A-Z]{3})[\s].*$'
f = open('textbase_1a.rtf', 'Ur')
fileLines = f.readlines()
# get the matching line numbers, and store in usefulLines
for i, line in enumerate(fileLines):
#line = line.decode('utf-16be') # this causes an error: I don't really know what file encoding the RTF file is in...
line = line.decode('mac_roman')
print line
if re.match(entryPattern, line):
# now retrieve the following lines, all the way up until we get a blank line
print "match: " + str(i)
usefulLines.append(i)
At the moment, this prints all the lines, but doesn't print anything with match - though it should match. Also, the lines are being printed with '/par' at the start, for some reason. When I try printing them to an output file, they look very strange.
Part of the problem is that I don't know what encoding to specify. How can I find this out?
If I use entryPattern = '^.*$' then I do get matches.
Can anyone help?
|
[
"You did not even decode the RTF file. RTFs are not just simple text files. A file containing \"äöü\", for example, contains this:\n\n{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1031{\\fonttbl{\\f0\\fswiss\\fcharset0 Arial;}}\n{*\\generator Msftedit 5.41.15.1507;}\\viewkind4\\uc1\\pard\\f0\\fs20\\'e4\\'f6\\'fc\\par\n}\n\nwhen opened in a text editor. So the characters \"äöü\" are encoded as windows-1252 as declared at the beginning of the file (äöü = 0xE4 0xF6 0xFC).\nFor reading RTF you'll first need something that converts RTF to text (already asked here).\n"
] |
[
4
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0002192319_python_unicode.txt
|
Q:
install ImageUtils python
I am trying to install ImageUtils, I found the package but it doesn't have an installer with it. what is the procedure?
A:
The general approach to installing Python packages is to use easy_install, or pip; the choice between the two tends to get political, so I will just say I use pip. pip plays well with virtualenv, which is a tool that makes it much nicer to explore arbitrary Python packages.
In your case, (assuming you have installed virtualenv and pip) I would probably do something like the following (assumes Unix-like environment; there should be a Windows equivalent, but I'm not current on what it might be):
virtualenv iu-sandbox
pip install -E iu-sandbox ImageUtils
cd iu-sandbox
source bin/activate
Open the REPL and start exploring ImageUtils
|
install ImageUtils python
|
I am trying to install ImageUtils, I found the package but it doesn't have an installer with it. what is the procedure?
|
[
"The general approach to installing Python packages is to use easy_install, or pip; the choice between the two tends to get political, so I will just say I use pip. pip plays well with virtualenv, which is a tool that makes it much nicer to explore arbitrary Python packages.\nIn your case, (assuming you have installed virtualenv and pip) I would probably do something like the following (assumes Unix-like environment; there should be a Windows equivalent, but I'm not current on what it might be):\n\nvirtualenv iu-sandbox\npip install -E iu-sandbox ImageUtils\ncd iu-sandbox\nsource bin/activate\nOpen the REPL and start exploring ImageUtils\n\n"
] |
[
0
] |
[] |
[] |
[
"image",
"python"
] |
stackoverflow_0002192373_image_python.txt
|
Q:
Preventing an Active Directory user from changing his/her password using DirectoryServices
When creating Active Directory users from a script, I also need to set the option that they can't change their passwords. Via the administrative GUI this is easily accomplished, by checking "User cannot change password". Programmatically however, it's another story. I've found a recipe which involves interacting with the ADSI COM API, but for technical reasons I would like to accomplish the same via the .NET API (short version: I'm not able to access the ADSI COM API from my script).
I have tried to translate the aforementioned recipe to pure .NET, as can be seen in this Python snippet, but it has no effect unfortunately:
dir_entry = System.DirectoryServices.DirectoryEntry(ad_user)
obj_sec = dir_entry.ObjectSecurity
# Password GUID
guid = System.Guid(System.String("ab721a53-1e2f-11d0-9819-00aa0040529b"))
for identity in (r"NT AUTHORITY\SELF", "EVERYONE"):
identity = System.Security.Principal.NTAccount(identity)
access_rule = System.DirectoryServices.ActiveDirectoryAccessRule(
identity,
System.DirectoryServices.ActiveDirectoryRights.ExtendedRight,
System.Security.AccessControl.AccessControlType.Deny,
guid
)
obj_sec.AddAccessRule(access_rule)
dir_entry.ObjectSecurity = obj_sec
dir_entry.CommitChanges()
Would greatly appreciate any help :)
A:
If you can use .NET 3.5 there's a new namespace in there called System.DirectoryServices.AccountManagment. The UserPrincipal class in that namespace will allow you to set "Cannot Change Password" simply by setting the boolean UserCannotChangePassword property to false.
|
Preventing an Active Directory user from changing his/her password using DirectoryServices
|
When creating Active Directory users from a script, I also need to set the option that they can't change their passwords. Via the administrative GUI this is easily accomplished, by checking "User cannot change password". Programmatically however, it's another story. I've found a recipe which involves interacting with the ADSI COM API, but for technical reasons I would like to accomplish the same via the .NET API (short version: I'm not able to access the ADSI COM API from my script).
I have tried to translate the aforementioned recipe to pure .NET, as can be seen in this Python snippet, but it has no effect unfortunately:
dir_entry = System.DirectoryServices.DirectoryEntry(ad_user)
obj_sec = dir_entry.ObjectSecurity
# Password GUID
guid = System.Guid(System.String("ab721a53-1e2f-11d0-9819-00aa0040529b"))
for identity in (r"NT AUTHORITY\SELF", "EVERYONE"):
identity = System.Security.Principal.NTAccount(identity)
access_rule = System.DirectoryServices.ActiveDirectoryAccessRule(
identity,
System.DirectoryServices.ActiveDirectoryRights.ExtendedRight,
System.Security.AccessControl.AccessControlType.Deny,
guid
)
obj_sec.AddAccessRule(access_rule)
dir_entry.ObjectSecurity = obj_sec
dir_entry.CommitChanges()
Would greatly appreciate any help :)
|
[
"If you can use .NET 3.5 there's a new namespace in there called System.DirectoryServices.AccountManagment. The UserPrincipal class in that namespace will allow you to set \"Cannot Change Password\" simply by setting the boolean UserCannotChangePassword property to false.\n"
] |
[
0
] |
[] |
[] |
[
".net",
"active_directory",
"python"
] |
stackoverflow_0002191969_.net_active_directory_python.txt
|
Q:
How can I capture iSight frames with Python in Snow Leopard?
I have the following PyObjC script:
from Foundation import NSObject
import QTKit
error = None
capture_session = QTKit.QTCaptureSession.alloc().init()
print 'capture_session', capture_session
device = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo)
print 'device', device, type(device)
success = device.open_(error)
print 'device open success', success, error
if not success:
raise Exception(error)
capture_device_input = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(device)
print 'capture_device_input', capture_device_input, capture_device_input.device()
success = capture_session.addInput_error_(capture_device_input, error)
print 'session add input success', success, error
if not success:
raise Exception(error)
capture_decompressed_video_output = QTKit.QTCaptureDecompressedVideoOutput.alloc().init()
print 'capture_decompressed_video_output', capture_decompressed_video_output
class Delegate(NSObject):
def captureOutput_didOutputVideoFrame_withSampleBuffer_fromConnection_(self, captureOutput, videoFrame, sampleBuffer, connection):
print videoFrame, sampleBuffer, connection
delegate = Delegate.alloc().init()
print 'delegate', delegate
capture_decompressed_video_output.setDelegate_(delegate)
print 'output delegate:', capture_decompressed_video_output.delegate()
success = capture_session.addOutput_error_(capture_decompressed_video_output, error)
print 'capture session add output success', success, error
if not success:
raise Exception(error)
print 'about to run session', capture_session, 'with inputs', capture_session.inputs(), 'and outputs', capture_session.outputs()
capture_session.startRunning()
print 'capture session is running?', capture_session.isRunning()
import time
time.sleep(10)
The program reports no errors, but iSight's green light is never activated and the delegate's frame capture callback is never called. Here's the output I get:
$ python prueba.py
capture_session <QTCaptureSession: 0x1006c16f0>
device Built-in iSight <objective-c class QTCaptureDALDevice at 0x7fff70366aa8>
device open success (True, None) None
capture_device_input <QTCaptureDeviceInput: 0x1002ae010> Built-in iSight
session add input success (True, None) None
capture_decompressed_video_output <QTCaptureDecompressedVideoOutput: 0x104239f10>
delegate <Delegate: 0x10423af50>
output delegate: <Delegate: 0x10423af50>
capture session add output success (True, None) None
about to run session <QTCaptureSession: 0x1006c16f0> with inputs (
"<QTCaptureDeviceInput: 0x1002ae010>"
) and outputs (
"<QTCaptureDecompressedVideoOutput: 0x104239f10>"
)
capture session is running? True
PS: Please don't answer I should try PySight, I have but it won't work because Xcode can't compile CocoaSequenceGrabber in 64bit.
A:
Your problem here is that you don't have an event loop. If you want to do this as a standalone script, you'll have to figure out how to create one. The PyObjC XCode templates automatically set that up for you with:
from PyObjCTools import AppHelper
AppHelper.runEventLoop()
Trying to insert that at the top of your script, however, shows that something inside AppHelper (probably NSApplicationMain) expects a plist file to extract the main class from. You can get that by creating a setup.py file and using py2app, something like this example from a PyObjc talk:
from distutils.core import setup
import py2app
plist = dict(
NSPrincipalClass='SillyBalls',
)
setup(
plugin=['SillyBalls.py'],
data_files=['English.lproj'],
options=dict(py2app=dict(
extension='.saver',
plist=plist,
)),
)
A:
You should give a try to motmot's camiface library from Andrew Straw. It also works with firewire cameras, but it works also with the isight, which is what you are looking for.
From the tutorial:
import motmot.cam_iface.cam_iface_ctypes as cam_iface
import numpy as np
mode_num = 0
device_num = 0
num_buffers = 32
cam = cam_iface.Camera(device_num,num_buffers,mode_num)
cam.start_camera()
frame = np.asarray(cam.grab_next_frame_blocking())
print 'grabbed frame with shape %s'%(frame.shape,)
|
How can I capture iSight frames with Python in Snow Leopard?
|
I have the following PyObjC script:
from Foundation import NSObject
import QTKit
error = None
capture_session = QTKit.QTCaptureSession.alloc().init()
print 'capture_session', capture_session
device = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo)
print 'device', device, type(device)
success = device.open_(error)
print 'device open success', success, error
if not success:
raise Exception(error)
capture_device_input = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(device)
print 'capture_device_input', capture_device_input, capture_device_input.device()
success = capture_session.addInput_error_(capture_device_input, error)
print 'session add input success', success, error
if not success:
raise Exception(error)
capture_decompressed_video_output = QTKit.QTCaptureDecompressedVideoOutput.alloc().init()
print 'capture_decompressed_video_output', capture_decompressed_video_output
class Delegate(NSObject):
def captureOutput_didOutputVideoFrame_withSampleBuffer_fromConnection_(self, captureOutput, videoFrame, sampleBuffer, connection):
print videoFrame, sampleBuffer, connection
delegate = Delegate.alloc().init()
print 'delegate', delegate
capture_decompressed_video_output.setDelegate_(delegate)
print 'output delegate:', capture_decompressed_video_output.delegate()
success = capture_session.addOutput_error_(capture_decompressed_video_output, error)
print 'capture session add output success', success, error
if not success:
raise Exception(error)
print 'about to run session', capture_session, 'with inputs', capture_session.inputs(), 'and outputs', capture_session.outputs()
capture_session.startRunning()
print 'capture session is running?', capture_session.isRunning()
import time
time.sleep(10)
The program reports no errors, but iSight's green light is never activated and the delegate's frame capture callback is never called. Here's the output I get:
$ python prueba.py
capture_session <QTCaptureSession: 0x1006c16f0>
device Built-in iSight <objective-c class QTCaptureDALDevice at 0x7fff70366aa8>
device open success (True, None) None
capture_device_input <QTCaptureDeviceInput: 0x1002ae010> Built-in iSight
session add input success (True, None) None
capture_decompressed_video_output <QTCaptureDecompressedVideoOutput: 0x104239f10>
delegate <Delegate: 0x10423af50>
output delegate: <Delegate: 0x10423af50>
capture session add output success (True, None) None
about to run session <QTCaptureSession: 0x1006c16f0> with inputs (
"<QTCaptureDeviceInput: 0x1002ae010>"
) and outputs (
"<QTCaptureDecompressedVideoOutput: 0x104239f10>"
)
capture session is running? True
PS: Please don't answer I should try PySight, I have but it won't work because Xcode can't compile CocoaSequenceGrabber in 64bit.
|
[
"Your problem here is that you don't have an event loop. If you want to do this as a standalone script, you'll have to figure out how to create one. The PyObjC XCode templates automatically set that up for you with:\nfrom PyObjCTools import AppHelper\nAppHelper.runEventLoop()\n\nTrying to insert that at the top of your script, however, shows that something inside AppHelper (probably NSApplicationMain) expects a plist file to extract the main class from. You can get that by creating a setup.py file and using py2app, something like this example from a PyObjc talk:\nfrom distutils.core import setup\nimport py2app\nplist = dict(\n NSPrincipalClass='SillyBalls',\n)\nsetup(\n plugin=['SillyBalls.py'],\n data_files=['English.lproj'],\n options=dict(py2app=dict(\n extension='.saver',\n plist=plist,\n )),\n)\n\n",
"You should give a try to motmot's camiface library from Andrew Straw. It also works with firewire cameras, but it works also with the isight, which is what you are looking for.\nFrom the tutorial:\nimport motmot.cam_iface.cam_iface_ctypes as cam_iface\nimport numpy as np\n\nmode_num = 0\ndevice_num = 0\nnum_buffers = 32\n\ncam = cam_iface.Camera(device_num,num_buffers,mode_num)\ncam.start_camera()\nframe = np.asarray(cam.grab_next_frame_blocking())\nprint 'grabbed frame with shape %s'%(frame.shape,)\n\n"
] |
[
3,
2
] |
[] |
[] |
[
"isight",
"osx_snow_leopard",
"pyobjc",
"python",
"qtkit"
] |
stackoverflow_0001576593_isight_osx_snow_leopard_pyobjc_python_qtkit.txt
|
Q:
How do Python's class closures work?
If I make a class against a local namespace, how exactly does it work? For instance:
>>> def foo():
... i = 1
... class bar(object):
... j = i
... return bar
...
>>> dis(foo)
2 0 LOAD_CONST 1 (1)
3 STORE_DEREF 0 (i)
3 6 LOAD_CONST 2 ('bar')
9 LOAD_GLOBAL 0 (object)
12 BUILD_TUPLE 1
15 LOAD_CLOSURE 0 (i)
18 BUILD_TUPLE 1
21 LOAD_CONST 3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
24 MAKE_CLOSURE 0
27 CALL_FUNCTION 0
30 BUILD_CLASS
31 STORE_FAST 0 (bar)
5 34 LOAD_FAST 0 (bar)
37 RETURN_VALUE
The particular lines I'm curious about are these:
15 LOAD_CLOSURE 0 (i)
18 BUILD_TUPLE 1
21 LOAD_CONST 3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
24 MAKE_CLOSURE 0
27 CALL_FUNCTION 0
30 BUILD_CLASS
I suppose the biggest thing that I'm wondering is what function is being made and then called? And is this function where the closures are attached to the class, or does that happen elsewhere?
A:
The whole class body, i.e.
j = i
is a code object, which gets loaded at offset 21 and then invoked at offset 27 via CALL_FUNCTION. The result of the invocation (the local namespace) is then used together with the class name and the bases to create the class. BUILD_CLASS takes three arguments, similar to the type(name, bases, dict) function:
Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute.
There's also a very detailed article "Notes on the Python Class Statement" explaining how class creation works.
|
How do Python's class closures work?
|
If I make a class against a local namespace, how exactly does it work? For instance:
>>> def foo():
... i = 1
... class bar(object):
... j = i
... return bar
...
>>> dis(foo)
2 0 LOAD_CONST 1 (1)
3 STORE_DEREF 0 (i)
3 6 LOAD_CONST 2 ('bar')
9 LOAD_GLOBAL 0 (object)
12 BUILD_TUPLE 1
15 LOAD_CLOSURE 0 (i)
18 BUILD_TUPLE 1
21 LOAD_CONST 3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
24 MAKE_CLOSURE 0
27 CALL_FUNCTION 0
30 BUILD_CLASS
31 STORE_FAST 0 (bar)
5 34 LOAD_FAST 0 (bar)
37 RETURN_VALUE
The particular lines I'm curious about are these:
15 LOAD_CLOSURE 0 (i)
18 BUILD_TUPLE 1
21 LOAD_CONST 3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
24 MAKE_CLOSURE 0
27 CALL_FUNCTION 0
30 BUILD_CLASS
I suppose the biggest thing that I'm wondering is what function is being made and then called? And is this function where the closures are attached to the class, or does that happen elsewhere?
|
[
"The whole class body, i.e.\nj = i\n\nis a code object, which gets loaded at offset 21 and then invoked at offset 27 via CALL_FUNCTION. The result of the invocation (the local namespace) is then used together with the class name and the bases to create the class. BUILD_CLASS takes three arguments, similar to the type(name, bases, dict) function:\n\nReturn a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute.\n\nThere's also a very detailed article \"Notes on the Python Class Statement\" explaining how class creation works.\n"
] |
[
2
] |
[] |
[] |
[
"bytecode",
"closures",
"python"
] |
stackoverflow_0002192822_bytecode_closures_python.txt
|
Q:
Python: urllib2.urlopen(url, data) Why do you have to urllib.urlencode() the data?
I thought that a post sent all the information in HTTP headers when you used post (I'm not well informed on this subject obviously), so I'm confused why you have to urlencode() the data to a key=value&key2=value2 format. How does that formatting come into play when using POST?:
# Fail
data = {'name': 'John Smith'}
urllib2.urlopen(foo_url, data)
but
# Success
data = {'name': 'John Smith'}
data = urllib.urlencode(data)
urllib2.urlopen(foo_url, data)
A:
It is related to the "Content-Type" header: the client must have an idea of how the POST data is encoded or else how would it know how to decode it?
The standard way of doing this is through application/x-www-form-urlencoded encoding format.
Now, if the question is "why do we need to encode?", the answer is "because we need to be able to delineate the payload in the HTTP container".
A:
Data must be in the standard application/x-www-form-urlencoded format. urlencode converts your args to a url-encoded string.
|
Python: urllib2.urlopen(url, data) Why do you have to urllib.urlencode() the data?
|
I thought that a post sent all the information in HTTP headers when you used post (I'm not well informed on this subject obviously), so I'm confused why you have to urlencode() the data to a key=value&key2=value2 format. How does that formatting come into play when using POST?:
# Fail
data = {'name': 'John Smith'}
urllib2.urlopen(foo_url, data)
but
# Success
data = {'name': 'John Smith'}
data = urllib.urlencode(data)
urllib2.urlopen(foo_url, data)
|
[
"It is related to the \"Content-Type\" header: the client must have an idea of how the POST data is encoded or else how would it know how to decode it?\nThe standard way of doing this is through application/x-www-form-urlencoded encoding format.\nNow, if the question is \"why do we need to encode?\", the answer is \"because we need to be able to delineate the payload in the HTTP container\".\n",
"Data must be in the standard application/x-www-form-urlencoded format. urlencode converts your args to a url-encoded string.\n"
] |
[
9,
2
] |
[] |
[] |
[
"python",
"urllib",
"urllib2"
] |
stackoverflow_0002192987_python_urllib_urllib2.txt
|
Q:
Creating a video file from a group of PGM files in python
My python program generates a collection of binary files. I create pgm (portable bitmap files) using this binary data. I would like to create a video using each of the pgm files as a frame in my video.
I have had a look an mencoder but I dont think it supports pgm files
Can anyone offer any advice.
A:
If "PGM" is identical with "Portable GrayMap Files", cross-browser command line video processing tool ffmpeg can decode them: List of FFMPeg Codecs on Wikipedia
Check out the FFMPEG FAQ: 3.2 How do I encode single pictures into movies?
On how to use FFMpeg with Python, check this SO question. There is a wrapper for Python, but I can't find any statements on how good it is.
If in doubt, just call it from the command line.
|
Creating a video file from a group of PGM files in python
|
My python program generates a collection of binary files. I create pgm (portable bitmap files) using this binary data. I would like to create a video using each of the pgm files as a frame in my video.
I have had a look an mencoder but I dont think it supports pgm files
Can anyone offer any advice.
|
[
"If \"PGM\" is identical with \"Portable GrayMap Files\", cross-browser command line video processing tool ffmpeg can decode them: List of FFMPeg Codecs on Wikipedia\nCheck out the FFMPEG FAQ: 3.2 How do I encode single pictures into movies?\nOn how to use FFMpeg with Python, check this SO question. There is a wrapper for Python, but I can't find any statements on how good it is. \nIf in doubt, just call it from the command line.\n"
] |
[
1
] |
[] |
[] |
[
"pgm",
"python"
] |
stackoverflow_0002193192_pgm_python.txt
|
Q:
How to initialize a QT thread in python
As per examples seen online, I've created a Worker thread. I'm looking for a thread to run my GUI while one thread executes my code. Worker thread is defined as:
class Worker(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.exiting = False
self.size = QSize(0, 0)
def __del__(self):
self.exiting = True
self.wait()
pretty simple. Within my Window class, I have this line in the __init__ function: self.thread = Worker(). However, I never do anything with that self.thread afterwards. What am I supposed to be doing with it? This does not seem to be laid out as nicely as other threading mechanisms..
A:
I imagine you're looking at the example here? But that example does "do something with that thread afterwards" -- it hooks up methods to respond to the signals the thread sends when it starts and finishes, in the class Worker it defines a run method that draws random stars , etc etc. Not sure what you think is wrong with how this is "laid out"?
|
How to initialize a QT thread in python
|
As per examples seen online, I've created a Worker thread. I'm looking for a thread to run my GUI while one thread executes my code. Worker thread is defined as:
class Worker(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.exiting = False
self.size = QSize(0, 0)
def __del__(self):
self.exiting = True
self.wait()
pretty simple. Within my Window class, I have this line in the __init__ function: self.thread = Worker(). However, I never do anything with that self.thread afterwards. What am I supposed to be doing with it? This does not seem to be laid out as nicely as other threading mechanisms..
|
[
"I imagine you're looking at the example here? But that example does \"do something with that thread afterwards\" -- it hooks up methods to respond to the signals the thread sends when it starts and finishes, in the class Worker it defines a run method that draws random stars , etc etc. Not sure what you think is wrong with how this is \"laid out\"?\n"
] |
[
2
] |
[] |
[] |
[
"multithreading",
"pyqt",
"python",
"qt"
] |
stackoverflow_0002193182_multithreading_pyqt_python_qt.txt
|
Q:
Why am I leaking memory with this python loop?
I am writing a custom file system crawler, which gets passed millions of globs to process through sys.stdin. I'm finding that when running the script, its memory usage increases massively over time and the whole thing crawls practically to a halt. I've written a minimal case below which shows the problem. Am I doing something wrong, or have I found a bug in Python / the glob module? (I am using python 2.5.2).
#!/usr/bin/env python
import glob
import sys
import gc
previous_num_objects = 0
for count, line in enumerate(sys.stdin):
glob_result = glob.glob(line.rstrip('\n'))
current_num_objects = len(gc.get_objects())
new_objects = current_num_objects - previous_num_objects
print "(%d) This: %d, New: %d, Garbage: %d, Collection Counts: %s"\
% (count, current_num_objects, new_objects, len(gc.garbage), gc.get_count())
previous_num_objects = current_num_objects
The output looks like:
(0) This: 4042, New: 4042, Python Garbage: 0, Python Collection Counts: (660, 5, 0)
(1) This: 4061, New: 19, Python Garbage: 0, Python Collection Counts: (90, 6, 0)
(2) This: 4064, New: 3, Python Garbage: 0, Python Collection Counts: (127, 6, 0)
(3) This: 4067, New: 3, Python Garbage: 0, Python Collection Counts: (130, 6, 0)
(4) This: 4070, New: 3, Python Garbage: 0, Python Collection Counts: (133, 6, 0)
(5) This: 4073, New: 3, Python Garbage: 0, Python Collection Counts: (136, 6, 0)
(6) This: 4076, New: 3, Python Garbage: 0, Python Collection Counts: (139, 6, 0)
(7) This: 4079, New: 3, Python Garbage: 0, Python Collection Counts: (142, 6, 0)
(8) This: 4082, New: 3, Python Garbage: 0, Python Collection Counts: (145, 6, 0)
(9) This: 4085, New: 3, Python Garbage: 0, Python Collection Counts: (148, 6, 0)
Every 100th iteration, 100 objects are freed, so len(gc.get_objects() increases by 200 every 100 iterations. len(gc.garbage) never changes from 0. The 2nd generation collection count increases slowly, while the 0th and 1st counts go up and down.
A:
I tracked this down to the fnmatch module. glob.glob calls fnmatch to actually perform the globbing, and fnmatch has a cache of regular expressions which is never cleared. So in this usage, the cache was growing continuously and unchecked. I've filed a bug against the fnmatch library [1].
[1]: http://bugs.python.org/issue7846 Python Bug
A:
I cannot reproduce any actual leak on my system, but I think your "every 100th iteration, 100 objects are freed" is you hitting the cache for compiled regular expressions (via the glob module). If you peek at re.py you'll see _MAXCACHE defaults to 100, and by default the entire cache is blown away once you hit that (in _compile). If you call re.purge() before your gc calls you will probably see that effect go away.
(note I'm only suggesting re.purge() here to check that cache is affecting your gc results. It should not be necessary to have that in your actual code.)
I doubt that fixes your massive memory increase problem though.
|
Why am I leaking memory with this python loop?
|
I am writing a custom file system crawler, which gets passed millions of globs to process through sys.stdin. I'm finding that when running the script, its memory usage increases massively over time and the whole thing crawls practically to a halt. I've written a minimal case below which shows the problem. Am I doing something wrong, or have I found a bug in Python / the glob module? (I am using python 2.5.2).
#!/usr/bin/env python
import glob
import sys
import gc
previous_num_objects = 0
for count, line in enumerate(sys.stdin):
glob_result = glob.glob(line.rstrip('\n'))
current_num_objects = len(gc.get_objects())
new_objects = current_num_objects - previous_num_objects
print "(%d) This: %d, New: %d, Garbage: %d, Collection Counts: %s"\
% (count, current_num_objects, new_objects, len(gc.garbage), gc.get_count())
previous_num_objects = current_num_objects
The output looks like:
(0) This: 4042, New: 4042, Python Garbage: 0, Python Collection Counts: (660, 5, 0)
(1) This: 4061, New: 19, Python Garbage: 0, Python Collection Counts: (90, 6, 0)
(2) This: 4064, New: 3, Python Garbage: 0, Python Collection Counts: (127, 6, 0)
(3) This: 4067, New: 3, Python Garbage: 0, Python Collection Counts: (130, 6, 0)
(4) This: 4070, New: 3, Python Garbage: 0, Python Collection Counts: (133, 6, 0)
(5) This: 4073, New: 3, Python Garbage: 0, Python Collection Counts: (136, 6, 0)
(6) This: 4076, New: 3, Python Garbage: 0, Python Collection Counts: (139, 6, 0)
(7) This: 4079, New: 3, Python Garbage: 0, Python Collection Counts: (142, 6, 0)
(8) This: 4082, New: 3, Python Garbage: 0, Python Collection Counts: (145, 6, 0)
(9) This: 4085, New: 3, Python Garbage: 0, Python Collection Counts: (148, 6, 0)
Every 100th iteration, 100 objects are freed, so len(gc.get_objects() increases by 200 every 100 iterations. len(gc.garbage) never changes from 0. The 2nd generation collection count increases slowly, while the 0th and 1st counts go up and down.
|
[
"I tracked this down to the fnmatch module. glob.glob calls fnmatch to actually perform the globbing, and fnmatch has a cache of regular expressions which is never cleared. So in this usage, the cache was growing continuously and unchecked. I've filed a bug against the fnmatch library [1].\n[1]: http://bugs.python.org/issue7846 Python Bug\n",
"I cannot reproduce any actual leak on my system, but I think your \"every 100th iteration, 100 objects are freed\" is you hitting the cache for compiled regular expressions (via the glob module). If you peek at re.py you'll see _MAXCACHE defaults to 100, and by default the entire cache is blown away once you hit that (in _compile). If you call re.purge() before your gc calls you will probably see that effect go away.\n(note I'm only suggesting re.purge() here to check that cache is affecting your gc results. It should not be necessary to have that in your actual code.)\nI doubt that fixes your massive memory increase problem though.\n"
] |
[
7,
2
] |
[] |
[] |
[
"glob",
"memory",
"memory_leaks",
"python"
] |
stackoverflow_0002184063_glob_memory_memory_leaks_python.txt
|
Q:
Django admin authentication failure
logging into django admin fails when 'log in' button is pressed first
time, but pressing "back" and "log in' again - logs the user in
successfully.
I am deploying Django app with zc.buildout here, with a setup similar
to what is described here http://www.meppum.com/2009/jan/17/installing-django-ubuntu-intrepid/.
Nginx (listening on 127.0.0.1:8003) is running beyond Apache(listening
on 127.0.0.1:8001), configurations of both servers are provided at the
end of the post. I'm accessing my django app as 127.0.0.1:8003/.
So, 127.0.0.1:8003/admin/ opens django admin login form.
1)Entering username/pass, pressing "log in" redirects to (for some unknown reason?) 127.0.0.1/
admin, therefore ends up with nothing, as there is no server listening
on 80 port.
HTTP trace (after clicking login in: http://127.0.0.1:8003/admin/)
POST /admin/ HTTP/1.1
Host: 127.0.0.1:8003
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.17) Gecko/2010010604 Ubuntu/9.04 (jaunty) Firefox/3.0.17
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://127.0.0.1:8003/admin/
Cookie: JSESSIONID=0D287C17FBA82223AB7D5884EA534967; sessionid=c65c7af8ebde9e6bdf9c739a731d376b
Content-Type: application/x-www-form-urlencoded
Content-Length: 55
username=to&password=password&this_is_the_login_form=1
HTTP/1.x 302 FOUND
Server: nginx/0.8.29
Date: Mon, 01 Feb 2010 10:27:44 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Expires: Mon, 01 Feb 2010 10:27:44 GMT
Vary: Cookie
Etag: "d41d8cd98f00b204e9800998ecf8427e"
Cache-Control: max-age=0
Set-Cookie: sessionid=9db437da69c359136786696f90ba89f2; expires=Mon, 15-Feb-2010 10:27:44 GMT; Max-Age=1209600; Path=/
Last-Modified: Mon, 01 Feb 2010 10:27:44 GMT
Location: http://127.0.0.1/admin/
Content-Length: 0
2)Pressing browser's back , and 'log in' button once again (or
pressing browser's 'back' and 'refresh') logs in succesfully. HTTP trace:
POST /admin/ HTTP/1.1
Host: 127.0.0.1:8003
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.17) Gecko/2010010604 Ubuntu/9.04 (jaunty) Firefox/3.0.17
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://127.0.0.1:8003/admin/
Cookie: JSESSIONID=0D287C17FBA82223AB7D5884EA534967; sessionid=9db437da69c359136786696f90ba89f2
Content-Type: application/x-www-form-urlencoded
Content-Length: 55
username=to&password=password&this_is_the_login_form=1
HTTP/1.x 200 OK
Server: nginx/0.8.29
Date: Mon, 01 Feb 2010 10:52:02 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Expires: Mon, 01 Feb 2010 10:52:02 GMT
Vary: Cookie
Etag: "3355a46fb32d7cb6ab21262c359d9eec"
Cache-Control: max-age=0
Last-Modified: Mon, 01 Feb 2010 10:52:02 GMT
It looks like that's a cookie-related issue, but, i guess, the root of
the problem might as well lie in the apache and/or nginx config as well.
Any ideas how to make the admin log-in form work immediately?
Cheers!
to
P.S.configs:
apache vhost configuration:
<VirtualHost *:8001>
<Directory /home/toinbis/Desktop/programming/project/runtime/
htdocs/django_wsgi/>
Order deny,allow
Allow from all
</Directory>
WSGIDaemonProcess tsd user=www-data group=www-data threads=25
WSGIProcessGroup tsd
WSGIScriptAlias / /home/toinbis/Desktop/programming/project/
runtime/htdocs/django_wsgi/djproject.wsgi
LogLevel warn
ErrorLog /home/toinbis/Desktop/programming/project/runtime/logs/
apache_tsd_error.log
CustomLog /home/toinbis/Desktop/programming/project/runtime/logs/
apache_tsd_access.log combined
ServerName localhost
</VirtualHost>
nginx configuration:
daemon off;
#user www-data;
worker_processes 2;
error_log /home/toinbis/Desktop/programming/project/runtime/logs/
nginx_general_error.log;
pid /home/toinbis/Desktop/programming/project/runtime/var/pids/
nginx.pid;
events {
worker_connections 1024;
#server_names_hash_bucket_size: 128;
}
http {
include /home/toinbis/Desktop/programming/project/runtime/
etc/nginx_conf/mime.types;
default_type application/octet-stream;
access_log /home/toinbis/Desktop/programming/project/runtime/logs/
nginx_access.log;
error_log /home/toinbis/Desktop/programming/project/runtime/logs/
nginx_error.log;
sendfile on;
tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 2;
tcp_nodelay on;
server_names_hash_bucket_size 128;
#server_name_hashes 128;
gzip on;
gzip_comp_level 2;
gzip_proxied any;
gzip_disable "MSIE [1-6]\.(?!.*SV1)"; #iš ubuntu
gzip_types text/plain text/css application/x-javascript text/xml
application/xml application/xml+rss text/javascript;
upstream backend {
server 127.0.0.1:8001;
}
server {
listen 8003;
server_name localhost;
error_log /home/toinbis/Desktop/programming/project/
runtime/logs/project_nginx_error.log;
access_log /home/toinbis/Desktop/programming/project/
runtime/logs/project_nginx_access.log;
location / {
proxy_pass http://backend/;
include /home/toinbis/Desktop/programming/
project/runtime/etc/nginx_conf/nginx_proxy_1.conf;
}
location /media/ {
root /home/toinbis/Desktop/programming/project/
src/tsd/core/;
}
}
}
cheers,
to
A:
Your settings are incorrect. Django believes that it runs on port 80. Look at this line in the first HTTP response:
Location: http://127.0.0.1/admin/
Unfortunately, I can't understand right now why this happens. I prefer just to step throught the relevant Django code with a debugger in such cases.
A:
@Eugene Morozov has pointed out the end result of the problem, but I think the solution lies deeper.
The Location header being returned is incorrect:
Location: http://127.0.0.1/admin/
This is clearly missing the port number. Unfortunately, it is hard to tell exactly where this is coming from. You may be running into either Nginx or Apache automagically altering the Location header. I'd suggest doing the following to see where the problem crops up:
Clear your cookies before each time you log in, or you may get a false positive.
Go directly to your Apache instance and see if the problem persists.
http://127.0.0.1:8001/admin/
If the location header does not have a port on it:
Fire up the Django development server on some random port (8005, for example) and see if the problem persists:
If the problem persists, it is in your code.
If the problem does not persist, Apache is either doing something weird or WSGI/Django isn't getting all the information it needs to determine the port number.
Make sure that the wsgi script and the django app can both see the port number in the environment.
If the location header has a port in it:
Nginx is stripping it off for some reason.
Try cutting Apache out of the loop, you probably don't need it.
Fire up Django as a FastCGI server and connect Nginx to that instead of Apache.
This will actually lower some of the overhead on your server (less request passing, extra threads, memory use, etc).
Fairly good setup guide over here.
Ninja Edit!
Not sure if this will help, but it seems there is an option in Nginx for ignoring the port number in redirects. The URL is dead, so I'm pasting this from over here.
http://wiki.codemongers.com/NginxHttpCoreModule#port_in_redirect
syntax: port_in_redirect [ on|off ]
default: port_in_redirect on
context: http, server, location
Directive allows or prevents port
indication in redirects handled by
nginx.
A:
Euge, James,
thanks a lot for your help once again!
The solution turned out to be described here: changing proxy_set_headerHost $host; to proxy_set_headerHost $host:$server_port; did the trick!
|
Django admin authentication failure
|
logging into django admin fails when 'log in' button is pressed first
time, but pressing "back" and "log in' again - logs the user in
successfully.
I am deploying Django app with zc.buildout here, with a setup similar
to what is described here http://www.meppum.com/2009/jan/17/installing-django-ubuntu-intrepid/.
Nginx (listening on 127.0.0.1:8003) is running beyond Apache(listening
on 127.0.0.1:8001), configurations of both servers are provided at the
end of the post. I'm accessing my django app as 127.0.0.1:8003/.
So, 127.0.0.1:8003/admin/ opens django admin login form.
1)Entering username/pass, pressing "log in" redirects to (for some unknown reason?) 127.0.0.1/
admin, therefore ends up with nothing, as there is no server listening
on 80 port.
HTTP trace (after clicking login in: http://127.0.0.1:8003/admin/)
POST /admin/ HTTP/1.1
Host: 127.0.0.1:8003
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.17) Gecko/2010010604 Ubuntu/9.04 (jaunty) Firefox/3.0.17
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://127.0.0.1:8003/admin/
Cookie: JSESSIONID=0D287C17FBA82223AB7D5884EA534967; sessionid=c65c7af8ebde9e6bdf9c739a731d376b
Content-Type: application/x-www-form-urlencoded
Content-Length: 55
username=to&password=password&this_is_the_login_form=1
HTTP/1.x 302 FOUND
Server: nginx/0.8.29
Date: Mon, 01 Feb 2010 10:27:44 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Expires: Mon, 01 Feb 2010 10:27:44 GMT
Vary: Cookie
Etag: "d41d8cd98f00b204e9800998ecf8427e"
Cache-Control: max-age=0
Set-Cookie: sessionid=9db437da69c359136786696f90ba89f2; expires=Mon, 15-Feb-2010 10:27:44 GMT; Max-Age=1209600; Path=/
Last-Modified: Mon, 01 Feb 2010 10:27:44 GMT
Location: http://127.0.0.1/admin/
Content-Length: 0
2)Pressing browser's back , and 'log in' button once again (or
pressing browser's 'back' and 'refresh') logs in succesfully. HTTP trace:
POST /admin/ HTTP/1.1
Host: 127.0.0.1:8003
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.17) Gecko/2010010604 Ubuntu/9.04 (jaunty) Firefox/3.0.17
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://127.0.0.1:8003/admin/
Cookie: JSESSIONID=0D287C17FBA82223AB7D5884EA534967; sessionid=9db437da69c359136786696f90ba89f2
Content-Type: application/x-www-form-urlencoded
Content-Length: 55
username=to&password=password&this_is_the_login_form=1
HTTP/1.x 200 OK
Server: nginx/0.8.29
Date: Mon, 01 Feb 2010 10:52:02 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Expires: Mon, 01 Feb 2010 10:52:02 GMT
Vary: Cookie
Etag: "3355a46fb32d7cb6ab21262c359d9eec"
Cache-Control: max-age=0
Last-Modified: Mon, 01 Feb 2010 10:52:02 GMT
It looks like that's a cookie-related issue, but, i guess, the root of
the problem might as well lie in the apache and/or nginx config as well.
Any ideas how to make the admin log-in form work immediately?
Cheers!
to
P.S.configs:
apache vhost configuration:
<VirtualHost *:8001>
<Directory /home/toinbis/Desktop/programming/project/runtime/
htdocs/django_wsgi/>
Order deny,allow
Allow from all
</Directory>
WSGIDaemonProcess tsd user=www-data group=www-data threads=25
WSGIProcessGroup tsd
WSGIScriptAlias / /home/toinbis/Desktop/programming/project/
runtime/htdocs/django_wsgi/djproject.wsgi
LogLevel warn
ErrorLog /home/toinbis/Desktop/programming/project/runtime/logs/
apache_tsd_error.log
CustomLog /home/toinbis/Desktop/programming/project/runtime/logs/
apache_tsd_access.log combined
ServerName localhost
</VirtualHost>
nginx configuration:
daemon off;
#user www-data;
worker_processes 2;
error_log /home/toinbis/Desktop/programming/project/runtime/logs/
nginx_general_error.log;
pid /home/toinbis/Desktop/programming/project/runtime/var/pids/
nginx.pid;
events {
worker_connections 1024;
#server_names_hash_bucket_size: 128;
}
http {
include /home/toinbis/Desktop/programming/project/runtime/
etc/nginx_conf/mime.types;
default_type application/octet-stream;
access_log /home/toinbis/Desktop/programming/project/runtime/logs/
nginx_access.log;
error_log /home/toinbis/Desktop/programming/project/runtime/logs/
nginx_error.log;
sendfile on;
tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 2;
tcp_nodelay on;
server_names_hash_bucket_size 128;
#server_name_hashes 128;
gzip on;
gzip_comp_level 2;
gzip_proxied any;
gzip_disable "MSIE [1-6]\.(?!.*SV1)"; #iš ubuntu
gzip_types text/plain text/css application/x-javascript text/xml
application/xml application/xml+rss text/javascript;
upstream backend {
server 127.0.0.1:8001;
}
server {
listen 8003;
server_name localhost;
error_log /home/toinbis/Desktop/programming/project/
runtime/logs/project_nginx_error.log;
access_log /home/toinbis/Desktop/programming/project/
runtime/logs/project_nginx_access.log;
location / {
proxy_pass http://backend/;
include /home/toinbis/Desktop/programming/
project/runtime/etc/nginx_conf/nginx_proxy_1.conf;
}
location /media/ {
root /home/toinbis/Desktop/programming/project/
src/tsd/core/;
}
}
}
cheers,
to
|
[
"Your settings are incorrect. Django believes that it runs on port 80. Look at this line in the first HTTP response:\nLocation: http://127.0.0.1/admin/\n\nUnfortunately, I can't understand right now why this happens. I prefer just to step throught the relevant Django code with a debugger in such cases.\n",
"@Eugene Morozov has pointed out the end result of the problem, but I think the solution lies deeper.\nThe Location header being returned is incorrect:\nLocation: http://127.0.0.1/admin/\n\nThis is clearly missing the port number. Unfortunately, it is hard to tell exactly where this is coming from. You may be running into either Nginx or Apache automagically altering the Location header. I'd suggest doing the following to see where the problem crops up:\n\nClear your cookies before each time you log in, or you may get a false positive.\nGo directly to your Apache instance and see if the problem persists.\n\n\nhttp://127.0.0.1:8001/admin/\nIf the location header does not have a port on it:\n\n\nFire up the Django development server on some random port (8005, for example) and see if the problem persists:\n\n\nIf the problem persists, it is in your code.\nIf the problem does not persist, Apache is either doing something weird or WSGI/Django isn't getting all the information it needs to determine the port number.\n\n\nMake sure that the wsgi script and the django app can both see the port number in the environment.\n\n\n\nIf the location header has a port in it:\n\n\nNginx is stripping it off for some reason.\nTry cutting Apache out of the loop, you probably don't need it.\n\n\nFire up Django as a FastCGI server and connect Nginx to that instead of Apache. \n\n\nThis will actually lower some of the overhead on your server (less request passing, extra threads, memory use, etc).\nFairly good setup guide over here.\n\n\n\n\n\nNinja Edit!\nNot sure if this will help, but it seems there is an option in Nginx for ignoring the port number in redirects. The URL is dead, so I'm pasting this from over here.\n\nhttp://wiki.codemongers.com/NginxHttpCoreModule#port_in_redirect\n\nsyntax: port_in_redirect [ on|off ]\ndefault: port_in_redirect on\ncontext: http, server, location\n\n\nDirective allows or prevents port\n indication in redirects handled by \n nginx.\n\n",
"Euge, James,\nthanks a lot for your help once again!\nThe solution turned out to be described here: changing proxy_set_headerHost $host; to proxy_set_headerHost $host:$server_port; did the trick!\n"
] |
[
1,
1,
1
] |
[] |
[] |
[
"apache",
"buildout",
"django",
"nginx",
"python"
] |
stackoverflow_0002176172_apache_buildout_django_nginx_python.txt
|
Q:
How can I catch server json response while uploading image using Ajax?
I have a form which is loaded via jQuery from the external template file:
$('#imguploadform').html(' ').load('{% url upload_form %}');
In template it looks like this:
<img src="{{ MEDIA_URL }}img/misc/upload.png" alt="Illustration" title="myimage" />
<form id="uploadForm" enctype="multipart/form-data" method="post" action="upload_picture/">
{{ form.as_ul }}
<input type="submit" value="Upload" id="uploadImage" />
</form>
I'm trying to upload an image with ajax using jquery form plugin:
var submit_options = {
target: '#picworks',
dataType: 'json',
success: function() {
alert('It Works!');
}
};
$('#uploadForm').submit(function(){
$(this).ajaxSubmit(submit_options);
return false;
});
But then I want to return a json object from server and dynamically load into page an image using it's returned address. I've tried like this:
def upload_picture(request):
dest = save_original(request.FILES['image'])
form = UploadImageForm(request.POST, request.FILES)
res = json.dumps({
"path": dest,
})
return HttpResponse(res, mimetype='application/json')
The problem is that I can't catch a json response in javascript, so my browser shows me just an empty page with json dictionary content. What I'm doing wrong?
A:
Have your success callback take a parameter. That will be the response.
A:
var submit_options = {
target: '#picworks',
dataType: 'json',
success: function(response) {
alert('It Works!');
window.location.href = response.path;
}
};
A:
I solved the problem! The thing is that function which replace form submitting action with an ajax request is called earlier than the form loads from external file. So it should be like this:
$('#imguploadform').html(' ').load('{% url upload_form %}',
function(){
var submit_options = {
dataType: 'json',
success: update_dom
};
function update_dom(data) {
$('#picworks').html('<img src="' + data.path + '" alt="Illustration" />');
}
$('#uploadForm').submit(function(){
$(this).ajaxSubmit(submit_options);
return false;
});
});
|
How can I catch server json response while uploading image using Ajax?
|
I have a form which is loaded via jQuery from the external template file:
$('#imguploadform').html(' ').load('{% url upload_form %}');
In template it looks like this:
<img src="{{ MEDIA_URL }}img/misc/upload.png" alt="Illustration" title="myimage" />
<form id="uploadForm" enctype="multipart/form-data" method="post" action="upload_picture/">
{{ form.as_ul }}
<input type="submit" value="Upload" id="uploadImage" />
</form>
I'm trying to upload an image with ajax using jquery form plugin:
var submit_options = {
target: '#picworks',
dataType: 'json',
success: function() {
alert('It Works!');
}
};
$('#uploadForm').submit(function(){
$(this).ajaxSubmit(submit_options);
return false;
});
But then I want to return a json object from server and dynamically load into page an image using it's returned address. I've tried like this:
def upload_picture(request):
dest = save_original(request.FILES['image'])
form = UploadImageForm(request.POST, request.FILES)
res = json.dumps({
"path": dest,
})
return HttpResponse(res, mimetype='application/json')
The problem is that I can't catch a json response in javascript, so my browser shows me just an empty page with json dictionary content. What I'm doing wrong?
|
[
"Have your success callback take a parameter. That will be the response.\n",
"var submit_options = {\n target: '#picworks',\n dataType: 'json',\n success: function(response) { \n alert('It Works!');\n window.location.href = response.path;\n } \n};\n\n",
"I solved the problem! The thing is that function which replace form submitting action with an ajax request is called earlier than the form loads from external file. So it should be like this:\n$('#imguploadform').html(' ').load('{% url upload_form %}', \n\n function(){\n var submit_options = {\n dataType: 'json',\n success: update_dom\n };\n\n function update_dom(data) { \n $('#picworks').html('<img src=\"' + data.path + '\" alt=\"Illustration\" />');\n }\n\n $('#uploadForm').submit(function(){\n $(this).ajaxSubmit(submit_options);\n return false;\n });\n\n});\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"django",
"image",
"python",
"upload"
] |
stackoverflow_0002187211_django_image_python_upload.txt
|
Q:
How to launch a background process in Python with a delayed invocation?
Ok, this is a bit of a thorny problem. I need to launch a backgrounded process that will (1) wait N secs, and then (2) execute some command. Additionally, I need to capture the pid of the background process itself, because when the parent process finishes it will kill the backgrounded process if necessary. It looks a bit like this in shell syntax:
(sleep 15 && run_some_cmd) & # launch bg process
bg_pid=$! # capture the bg pid
# do some stuff here...
kill -9 $bg_pid # and kill the bg_pid if necessary
So that's the launch in shell. However, I'm trying to do this in Python. The tricky thing is that since I need to capture the bg pid, I can't use os.system() or os.fork(), since in each case the parent process does not have access to the pid of the child. I'm trying to get it to work with subprocess.Popen(), but it's a bit tricky given the "sleep 15" portion.
Any ideas?
A:
I can't use os.system() or os.fork(), since in each case the parent process does not have access to the pid of the child.
Er, the parent gets the pid as a return value from fork().
In any case, I would suggest using the subprocess module. It gives you access to the pid via the pid attribute of the Popen object. You can use the os.kill() function to send a signal to a process (to kill it).
Originally, I included a comment to the effect of "subprocess is preferable because it works on windows and fork() doesn't". This was removed almost immediately, because while the subprocess module works, os.kill() doesn't. However, you can work around this by defining a kill function for Windows, as well, as suggested here and (somewhat ironically) by Alex Martelli himself here. So now I can in fact declare that subprocess has the advantage of being more cross-platform, and this makes it somewhat cool.
Of course, if you use Alex Martelli's answer for this question, the ability to run on Windows is reduced again, as you're relying on features of the system shell (cygwin always is an option, of course).
A:
When you give shell as True to subprocess.Popen, the command you execute can be the same as you're executing directly in the shell in your example, i.e., (sleep 15 && run_some_cmd) should be fine.
|
How to launch a background process in Python with a delayed invocation?
|
Ok, this is a bit of a thorny problem. I need to launch a backgrounded process that will (1) wait N secs, and then (2) execute some command. Additionally, I need to capture the pid of the background process itself, because when the parent process finishes it will kill the backgrounded process if necessary. It looks a bit like this in shell syntax:
(sleep 15 && run_some_cmd) & # launch bg process
bg_pid=$! # capture the bg pid
# do some stuff here...
kill -9 $bg_pid # and kill the bg_pid if necessary
So that's the launch in shell. However, I'm trying to do this in Python. The tricky thing is that since I need to capture the bg pid, I can't use os.system() or os.fork(), since in each case the parent process does not have access to the pid of the child. I'm trying to get it to work with subprocess.Popen(), but it's a bit tricky given the "sleep 15" portion.
Any ideas?
|
[
"\nI can't use os.system() or os.fork(), since in each case the parent process does not have access to the pid of the child. \n\nEr, the parent gets the pid as a return value from fork().\nIn any case, I would suggest using the subprocess module. It gives you access to the pid via the pid attribute of the Popen object. You can use the os.kill() function to send a signal to a process (to kill it).\nOriginally, I included a comment to the effect of \"subprocess is preferable because it works on windows and fork() doesn't\". This was removed almost immediately, because while the subprocess module works, os.kill() doesn't. However, you can work around this by defining a kill function for Windows, as well, as suggested here and (somewhat ironically) by Alex Martelli himself here. So now I can in fact declare that subprocess has the advantage of being more cross-platform, and this makes it somewhat cool.\nOf course, if you use Alex Martelli's answer for this question, the ability to run on Windows is reduced again, as you're relying on features of the system shell (cygwin always is an option, of course).\n",
"When you give shell as True to subprocess.Popen, the command you execute can be the same as you're executing directly in the shell in your example, i.e., (sleep 15 && run_some_cmd) should be fine.\n"
] |
[
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002193551_python.txt
|
Q:
Overcoming the "disadvantages" of string immutability
I want to change the value of a particular string index, but unfortunately
string[4] = "a"
raises a TypeError, because strings are immutable ("item assignment is not supported").
So instead I use the rather clumsy
string = string[:4] + "a" + string[4:]
Is there a better way of doing this?
A:
The strings in Python are immutable, just like numbers and tuples. This means that you can create them, move them around, but not change them. Why is this so ? For a few reasons (you can find a better discussion online):
By design, strings in Python are considered elemental and unchangeable. This spurs better, safer programming styles.
The immutability of strings has efficiency benefits, chiefly in the area of lower storage requirements.
It also makes strings safer to use as dictionary keys
If you look around the Python web a little, you’ll notice that the most frequent advice to "how to change my string" is "design your code so that you won’t have to change it". Fair enough, but what other options are there ? Here are a few:
name = name[:2] + ‘G’ + name[3:] - this is an inefficient way to do the job. Python’s slice semantics ensure that this works correctly in all cases (as long as your index is in range), but involving several string copies and concatenations, it’s hardly your best shot at efficient code. Although if you don’t care for that (and most chances are you don’t), it’s a solid solution.
Use the MutableString class from module UserString. While no more efficient than the previous method (it performs the same trick under the hood), it is more consistent syntactically with normal string usage.
Use a list instead of a string to store mutable data. Convert back and forth using list and join. Depending on what you really need, ord and chr may also be useful.
Use an array object. This is perhaps your best option if you use the string to hold constrained data, such as ‘binary’ bytes, and want fast code.
Plagiarized from my own page on Python insights :-)
A:
mystring=list("abcdef")
mystring[4]="Z"
print ''.join(mystring)
A:
>>> from UserString import MutableString
>>> s = MutableString('abcd')
>>> s[2] = 'e'
>>> print s
abed
|
Overcoming the "disadvantages" of string immutability
|
I want to change the value of a particular string index, but unfortunately
string[4] = "a"
raises a TypeError, because strings are immutable ("item assignment is not supported").
So instead I use the rather clumsy
string = string[:4] + "a" + string[4:]
Is there a better way of doing this?
|
[
"The strings in Python are immutable, just like numbers and tuples. This means that you can create them, move them around, but not change them. Why is this so ? For a few reasons (you can find a better discussion online):\n\nBy design, strings in Python are considered elemental and unchangeable. This spurs better, safer programming styles.\nThe immutability of strings has efficiency benefits, chiefly in the area of lower storage requirements.\nIt also makes strings safer to use as dictionary keys\n\nIf you look around the Python web a little, you’ll notice that the most frequent advice to \"how to change my string\" is \"design your code so that you won’t have to change it\". Fair enough, but what other options are there ? Here are a few:\n\nname = name[:2] + ‘G’ + name[3:] - this is an inefficient way to do the job. Python’s slice semantics ensure that this works correctly in all cases (as long as your index is in range), but involving several string copies and concatenations, it’s hardly your best shot at efficient code. Although if you don’t care for that (and most chances are you don’t), it’s a solid solution.\nUse the MutableString class from module UserString. While no more efficient than the previous method (it performs the same trick under the hood), it is more consistent syntactically with normal string usage.\nUse a list instead of a string to store mutable data. Convert back and forth using list and join. Depending on what you really need, ord and chr may also be useful.\nUse an array object. This is perhaps your best option if you use the string to hold constrained data, such as ‘binary’ bytes, and want fast code.\n\n\nPlagiarized from my own page on Python insights :-)\n",
"mystring=list(\"abcdef\")\nmystring[4]=\"Z\"\nprint ''.join(mystring)\n\n",
">>> from UserString import MutableString\n>>> s = MutableString('abcd')\n>>> s[2] = 'e'\n>>> print s\nabed\n\n"
] |
[
9,
3,
0
] |
[] |
[] |
[
"immutability",
"python",
"string"
] |
stackoverflow_0002193705_immutability_python_string.txt
|
Q:
How can I grap resident set size from Python on Solaris?
Calling resource.getrusage() from Python returns a 0 value for resident set size on Solaris and Linux systems. On Linux you can pull the RSS From /proc//status instead. Does anybody have a good way to pull RSS on Solaris, either similar or not to the Linux workaround?
A:
Maybe use Solaris's psinfo under /proc? (solaris proc(4) docs)
A:
Well...you can pull it from the pmap application by calling pmap -x. But I was looking more for a way to access the info directly in /proc from my app. The only way to do it is to access the /proc/<pid>/xmap file. Unfortunately, the data is stored as an array of prxmap structs...so either a Python C-module is in order or using the ctypes module. I'll post an update when I get one of those written.
|
How can I grap resident set size from Python on Solaris?
|
Calling resource.getrusage() from Python returns a 0 value for resident set size on Solaris and Linux systems. On Linux you can pull the RSS From /proc//status instead. Does anybody have a good way to pull RSS on Solaris, either similar or not to the Linux workaround?
|
[
"Maybe use Solaris's psinfo under /proc? (solaris proc(4) docs)\n",
"Well...you can pull it from the pmap application by calling pmap -x. But I was looking more for a way to access the info directly in /proc from my app. The only way to do it is to access the /proc/<pid>/xmap file. Unfortunately, the data is stored as an array of prxmap structs...so either a Python C-module is in order or using the ctypes module. I'll post an update when I get one of those written.\n"
] |
[
0,
0
] |
[] |
[] |
[
"getrusage",
"python",
"solaris"
] |
stackoverflow_0002180156_getrusage_python_solaris.txt
|
Q:
M2Crypto: AttributeError for load_dynamic_engine()
I am using M2Crypto-0.20.2. I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication making xmlrpc calls over ssl.
I am trying to load the PKCS#11 engine as well as the Aladdin module (see code below). But I get an error:
AttributeError: 'module' object has no attribute 'load_dynamic_engine'
from M2Crypto import SSL, m2
m2.load_dynamic_engine("dynamic","/usr/local/ssl/lib/engines/engine_pkcs11.so")
m2.load_dynamic_engine("pkcs11","/usr/lib/libeTPkcs11.so")
According to the M2Crypto documentation, this function should be available. This is the documentation I'm reading: http://www.heikkitoivonen.net/m2crypto/api/
Can anyone point me to the correct documentation or help with figuring out how to load the engines?
Thanks!
A:
I was reading the documentation wrong. The load_dynamic_engine() belong in the Engine module.
I changed the command and now get a different error:
Engine.load_dynamic_engine("dynamic","/usr/local/ssl/lib/engines/engine_pkcs11.so")
bad engine id
Engine.load_dynamic_engine("dynamic","/usr/local/ssl/lib/engines/engine_pkcs11.so")
File "/usr/local/lib/python2.4/site-packages/M2Crypto/Engine.py", line 92, in load_dynamic_engine
e.ctrl_cmd_string("LOAD", None)
File "/usr/local/lib/python2.4/site-packages/M2Crypto/Engine.py", line 38, in ctrl_cmd_string
raise EngineError(Err.get_error())
M2Crypto.Engine.EngineError: 23541:error:260B606D:engine routines:DYNAMIC_LOAD:init failed:eng_dyn.c:521:
Any idea what this means?
A:
I haven't used the Engine module myself, so I cannot give you any definite answers. However, you should take a look at test_engine.py module for some pointers. I am guessing that to load engines provided by OpenSSL you shouldn't use that form of load_dynamic_engine(), but either load_dynamic() or load_openssl(). You'd probably need load_dynamic_engine() only when loading 3rd party modules.
|
M2Crypto: AttributeError for load_dynamic_engine()
|
I am using M2Crypto-0.20.2. I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication making xmlrpc calls over ssl.
I am trying to load the PKCS#11 engine as well as the Aladdin module (see code below). But I get an error:
AttributeError: 'module' object has no attribute 'load_dynamic_engine'
from M2Crypto import SSL, m2
m2.load_dynamic_engine("dynamic","/usr/local/ssl/lib/engines/engine_pkcs11.so")
m2.load_dynamic_engine("pkcs11","/usr/lib/libeTPkcs11.so")
According to the M2Crypto documentation, this function should be available. This is the documentation I'm reading: http://www.heikkitoivonen.net/m2crypto/api/
Can anyone point me to the correct documentation or help with figuring out how to load the engines?
Thanks!
|
[
"I was reading the documentation wrong. The load_dynamic_engine() belong in the Engine module.\nI changed the command and now get a different error:\nEngine.load_dynamic_engine(\"dynamic\",\"/usr/local/ssl/lib/engines/engine_pkcs11.so\")\nbad engine id\nEngine.load_dynamic_engine(\"dynamic\",\"/usr/local/ssl/lib/engines/engine_pkcs11.so\")\n File \"/usr/local/lib/python2.4/site-packages/M2Crypto/Engine.py\", line 92, in load_dynamic_engine\n e.ctrl_cmd_string(\"LOAD\", None)\n File \"/usr/local/lib/python2.4/site-packages/M2Crypto/Engine.py\", line 38, in ctrl_cmd_string\n raise EngineError(Err.get_error())\nM2Crypto.Engine.EngineError: 23541:error:260B606D:engine routines:DYNAMIC_LOAD:init failed:eng_dyn.c:521:\nAny idea what this means?\n",
"I haven't used the Engine module myself, so I cannot give you any definite answers. However, you should take a look at test_engine.py module for some pointers. I am guessing that to load engines provided by OpenSSL you shouldn't use that form of load_dynamic_engine(), but either load_dynamic() or load_openssl(). You'd probably need load_dynamic_engine() only when loading 3rd party modules.\n"
] |
[
0,
0
] |
[] |
[] |
[
"m2crypto",
"openssl",
"python"
] |
stackoverflow_0002193181_m2crypto_openssl_python.txt
|
Q:
Python underlying analysis books/articles?
Does anyone know good books that discuss the underlying architectures, in-depth analysis of CPython implementation. Something like
how list / tuple / dict implemented (and performance comparison...)
OOP discussion in Python context
Sorry if it sounds like a silly question :(
A:
Python features are described and discussed in Python Enhancement Proposals ("PEPs") These describe the implementation, also PEPs often contain working Python Code to help explain the algorithm though the final implementation may be in C. If you need more details than can be gotten from the PEPs then you should take a look at the source code.
Note: PEPs are written from the perspective of what ever enhancement is being proposed rather than an overall description of the implementation. So for example there might a PEP for Dict-Comprehensions but not for Dicts as a whole. For a top down view of Python internals the source code is the place to go.
A:
You should absolutely, at some point in your Python career, read every word of the Python Data Model and the Python Execution Model. While not CPython-specific, these articles are essential to understanding Python deeply.
A:
Beautiful Code book has a nice explanation about how dicts are implemented.
A:
This doesn't directly answer your question but it's useful to know nevertheless:
The source code of CPython is well-written and well-documented, and there are some PEPs that shed light on parts of the implementation. You should really try just reading it.
|
Python underlying analysis books/articles?
|
Does anyone know good books that discuss the underlying architectures, in-depth analysis of CPython implementation. Something like
how list / tuple / dict implemented (and performance comparison...)
OOP discussion in Python context
Sorry if it sounds like a silly question :(
|
[
"Python features are described and discussed in Python Enhancement Proposals (\"PEPs\") These describe the implementation, also PEPs often contain working Python Code to help explain the algorithm though the final implementation may be in C. If you need more details than can be gotten from the PEPs then you should take a look at the source code.\nNote: PEPs are written from the perspective of what ever enhancement is being proposed rather than an overall description of the implementation. So for example there might a PEP for Dict-Comprehensions but not for Dicts as a whole. For a top down view of Python internals the source code is the place to go.\n",
"You should absolutely, at some point in your Python career, read every word of the Python Data Model and the Python Execution Model. While not CPython-specific, these articles are essential to understanding Python deeply.\n",
"Beautiful Code book has a nice explanation about how dicts are implemented.\n",
"This doesn't directly answer your question but it's useful to know nevertheless:\nThe source code of CPython is well-written and well-documented, and there are some PEPs that shed light on parts of the implementation. You should really try just reading it.\n"
] |
[
3,
3,
2,
2
] |
[] |
[] |
[
"architecture",
"comparison",
"performance",
"python"
] |
stackoverflow_0002193829_architecture_comparison_performance_python.txt
|
Q:
How to start a "drawing loop" in PyQt?
Often times when we're drawing a GUI, we want our GUI to update based on the data changing in our program. At the start of the program, let's say I've drawn my GUI based on my initial data. That data will be changing constantly, so how can I redraw my GUI constantly?
A:
The best way that I have found to do this is to run your core program in a QThread and use signals to communicate with your gui. Here is an example where I update a progress dialog as my main program does some stuff.
Here is a code excerpt from a project that I was working on. The basic idea is that I am adding a number of files to a library object and updating the progress as the files are added.
The action is started by the Library class. The tread that does the actual work is in the AddFilesThread.
Let me know if this is helpful. If you need I can try to put together a working example instead of a code excerpt.
If you want to see the full code that I used go here: hystrix_library.py. The diaglog class that I used is in that file. I can't say that this is necessarily the best way to do things, but it works well and is fairly easy to read.
class Library(QtCore.QObject):
"""
This class is used to store information on the libraries.
"""
def __init__(self):
QtCore.QObject.__init__(self)
def importUrls(self, url_list):
# Create a progress dialog
self.ui_progress = AddUrlsProgressDialog()
self.ui_progress.show()
self.ui_progress.raise_()
# Create the add files thread object.
self.add_files_thread = AddFilesThread()
# Connect the thread to the dialog.
self.connect(self.add_files_thread
,QtCore.SIGNAL('updateDialog')
,self.ui_progress.setDialog)
self.connect(self.add_files_thread
,QtCore.SIGNAL('updateValue')
,self.ui_progress.setValue)
self.connect(self.add_files_thread
,QtCore.SIGNAL('finished')
,self.ui_progress.setFinished)
self.connect(self.add_files_thread
,QtCore.SIGNAL('canceled')
,self.ui_progress.closeNow)
# Connect the dialog to the thread
self.connect(self.ui_progress
,QtCore.SIGNAL('cancel')
,self.add_files_thread.cancelRequest)
# Start the thread
self.add_files_thread.start()
class AddFilesThread(QtCore.QThread):
def __init__(self, parent=None):
QtCore.QThread.__init__(self, parent)
self.cancel_request = False
def __del__(self):
self.wait()
def run(self):
try:
self.main()
except:
print 'AddFilesThread broke yo.'
self.cancelNow(force=True)
traceback.print_exc()
def main(self):
num_added = 0
for local_path in self.path_list:
# First Setup the dialog
status_label = 'Finding files to add . . .'
dialog_update = (status_label, (0,0), 0)
self.emit(QtCore.SIGNAL('updateDialog'), dialog_update)
# Do a recursive search.
all_files = hystrix_file.getFiles()
num_files = len(all_files)
if self.cancelNow():
return
status_label = '%d files found.\nExtracting tags . . .' %(num_files)
dialog_update = (status_label, (0,num_files), 0)
self.emit(QtCore.SIGNAL('updateDialog'), dialog_update)
num_added = 0
for index, filename in enumerate(all_files):
try:
metadata = hystrix_tags.getMetadata(filename)
# Here I would add the metadata to my library.
except:
traceback.print_exc()
print('Could not extract Metadata from file.')
continue
# This should be sent to a progress widget
if index % 1 == 0:
self.emit(QtCore.SIGNAL('updateValue'), index)
# Check if a cancel signal has been recieved
if self.cancelNow():
return
status_label = 'Finished. Added %d files.' %(num_added)
dialog_update = ( status_label, (0,num_added), num_added)
self.emit(QtCore.SIGNAL('updateDialog'), dialog_update)
self.emit(QtCore.SIGNAL('finished'))
def cancelRequest(self):
self.cancel_request = True
def cancelNow(self, force=False):
if self.cancel_request or force:
self.emit(QtCore.SIGNAL('canceled'))
return True
else:
return False
A:
You could create a thread to update the GUI constantly, just pass to it references to the graphical widgets that need to be updated
|
How to start a "drawing loop" in PyQt?
|
Often times when we're drawing a GUI, we want our GUI to update based on the data changing in our program. At the start of the program, let's say I've drawn my GUI based on my initial data. That data will be changing constantly, so how can I redraw my GUI constantly?
|
[
"The best way that I have found to do this is to run your core program in a QThread and use signals to communicate with your gui. Here is an example where I update a progress dialog as my main program does some stuff.\nHere is a code excerpt from a project that I was working on. The basic idea is that I am adding a number of files to a library object and updating the progress as the files are added.\nThe action is started by the Library class. The tread that does the actual work is in the AddFilesThread.\nLet me know if this is helpful. If you need I can try to put together a working example instead of a code excerpt.\n\n\nIf you want to see the full code that I used go here: hystrix_library.py. The diaglog class that I used is in that file. I can't say that this is necessarily the best way to do things, but it works well and is fairly easy to read.\nclass Library(QtCore.QObject):\n \"\"\"\n This class is used to store information on the libraries.\n \"\"\"\n def __init__(self):\n QtCore.QObject.__init__(self)\n\n def importUrls(self, url_list):\n\n # Create a progress dialog\n self.ui_progress = AddUrlsProgressDialog()\n self.ui_progress.show()\n self.ui_progress.raise_()\n\n # Create the add files thread object.\n self.add_files_thread = AddFilesThread()\n\n # Connect the thread to the dialog.\n self.connect(self.add_files_thread\n ,QtCore.SIGNAL('updateDialog')\n ,self.ui_progress.setDialog)\n\n self.connect(self.add_files_thread\n ,QtCore.SIGNAL('updateValue')\n ,self.ui_progress.setValue)\n\n self.connect(self.add_files_thread\n ,QtCore.SIGNAL('finished')\n ,self.ui_progress.setFinished)\n\n self.connect(self.add_files_thread\n ,QtCore.SIGNAL('canceled')\n ,self.ui_progress.closeNow)\n\n # Connect the dialog to the thread\n self.connect(self.ui_progress\n ,QtCore.SIGNAL('cancel')\n ,self.add_files_thread.cancelRequest) \n\n # Start the thread\n self.add_files_thread.start()\n\n\n\n\nclass AddFilesThread(QtCore.QThread):\n\n def __init__(self, parent=None):\n QtCore.QThread.__init__(self, parent)\n\n self.cancel_request = False\n\n def __del__(self):\n self.wait()\n\n def run(self):\n try:\n self.main()\n except:\n print 'AddFilesThread broke yo.'\n self.cancelNow(force=True)\n traceback.print_exc()\n\n def main(self):\n num_added = 0\n for local_path in self.path_list:\n # First Setup the dialog\n status_label = 'Finding files to add . . .'\n dialog_update = (status_label, (0,0), 0)\n self.emit(QtCore.SIGNAL('updateDialog'), dialog_update)\n\n # Do a recursive search.\n all_files = hystrix_file.getFiles()\n num_files = len(all_files)\n\n if self.cancelNow():\n return\n\n status_label = '%d files found.\\nExtracting tags . . .' %(num_files)\n dialog_update = (status_label, (0,num_files), 0)\n self.emit(QtCore.SIGNAL('updateDialog'), dialog_update)\n\n num_added = 0\n for index, filename in enumerate(all_files):\n try:\n metadata = hystrix_tags.getMetadata(filename)\n # Here I would add the metadata to my library.\n except:\n traceback.print_exc()\n print('Could not extract Metadata from file.')\n continue\n\n # This should be sent to a progress widget\n if index % 1 == 0:\n self.emit(QtCore.SIGNAL('updateValue'), index)\n\n # Check if a cancel signal has been recieved\n if self.cancelNow():\n return\n\n status_label = 'Finished. Added %d files.' %(num_added)\n dialog_update = ( status_label, (0,num_added), num_added)\n self.emit(QtCore.SIGNAL('updateDialog'), dialog_update)\n\n self.emit(QtCore.SIGNAL('finished'))\n\n def cancelRequest(self):\n self.cancel_request = True\n\n def cancelNow(self, force=False):\n if self.cancel_request or force:\n self.emit(QtCore.SIGNAL('canceled'))\n return True\n else:\n return False\n\n",
"You could create a thread to update the GUI constantly, just pass to it references to the graphical widgets that need to be updated\n"
] |
[
1,
0
] |
[] |
[] |
[
"pyqt",
"python"
] |
stackoverflow_0002192993_pyqt_python.txt
|
Q:
Checking for properties' validity in Python classes
Where should I write codes for checking validity of class' properties? (For examples: "amount" should be a positive integer, "email" should be a string with correct e-mail formatting) At the setter methods, At somewhere I use that (using try/catch), or others.
If I check validity at setter methods, it may be looked ugly (like type checking). But if I check it when using it, duplicated code may appeared when it is used many times.
(Sorry for my poor English.)
A:
Definitely do it in the setter, if you need to do it at all.
First, the setter is probably called less often than the getters, so you're doing less work.
Second, you catch the problem earlier.
Third, it keeps the internal state of the object consistent. Keeping out bad data means you know that your object is "right".
A:
If it looks like ugly type checking, that may be because it is. If "amount" absolutely needs to be a positive integer, and the rest of the module will fail badly if it is not, then you need to do some type checking.
The python way of doing this, though, is only to check for the actual properties that you require.
In the positive integer example, that means not checking that the value is an Int object, but checking instead that it has a value, and that the value is > 0. This lets other programmers pass your methods objects that act like numbers, without strictly constraining their type.
The same thing goes for the email example -- check that it is properly formatted (matches whatever email regex you are using), but don't insist that it is an instance of the Str class. Don't insist on anything in your validity checking except properties that you are actually going to use.
|
Checking for properties' validity in Python classes
|
Where should I write codes for checking validity of class' properties? (For examples: "amount" should be a positive integer, "email" should be a string with correct e-mail formatting) At the setter methods, At somewhere I use that (using try/catch), or others.
If I check validity at setter methods, it may be looked ugly (like type checking). But if I check it when using it, duplicated code may appeared when it is used many times.
(Sorry for my poor English.)
|
[
"Definitely do it in the setter, if you need to do it at all.\nFirst, the setter is probably called less often than the getters, so you're doing less work. \nSecond, you catch the problem earlier.\nThird, it keeps the internal state of the object consistent. Keeping out bad data means you know that your object is \"right\".\n",
"If it looks like ugly type checking, that may be because it is. If \"amount\" absolutely needs to be a positive integer, and the rest of the module will fail badly if it is not, then you need to do some type checking.\nThe python way of doing this, though, is only to check for the actual properties that you require.\nIn the positive integer example, that means not checking that the value is an Int object, but checking instead that it has a value, and that the value is > 0. This lets other programmers pass your methods objects that act like numbers, without strictly constraining their type.\nThe same thing goes for the email example -- check that it is properly formatted (matches whatever email regex you are using), but don't insist that it is an instance of the Str class. Don't insist on anything in your validity checking except properties that you are actually going to use.\n"
] |
[
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002194479_python.txt
|
Q:
Is there something similar to python's enumerate for linq
In python I can easily get an index when iterating e.g.
>>> letters = ['a', 'b', 'c']
>>> [(char, i) for i, char in enumerate(letters)]
[('a', 0), ('b', 1), ('c', 2)]
How can I do something similar with linq?
A:
Sure. There is an overload of Enumerable.Select that takes a Func<TSource, int, TResult> to project an element together with its index:
For example:
char[] letters = new[] { 'a', 'b', 'c' };
var enumerate = letters.Select((c, i) => new { Char = c, Index = i });
foreach (var result in enumerate) {
Console.WriteLine(
String.Format("Char = {0}, Index = {1}", result.Char, result.Index)
);
}
Output:
Char = a, Index = 0
Char = b, Index = 1
Char = c, Index = 2
A:
You can do this with the overload of Enumerable.Select which provides an index variable. This provides access to the index, which you can use to generate a new anonymous type. The following compiles and runs properly:
static void Main()
{
var letters = new char[] { 'a', 'b', 'c' };
var results = letters.Select((l, i) => new { Letter = l, Index = i });
foreach (var result in results)
{
Console.WriteLine("{0} / {1}", result.Letter, result.Index);
}
Console.ReadKey();
}
|
Is there something similar to python's enumerate for linq
|
In python I can easily get an index when iterating e.g.
>>> letters = ['a', 'b', 'c']
>>> [(char, i) for i, char in enumerate(letters)]
[('a', 0), ('b', 1), ('c', 2)]
How can I do something similar with linq?
|
[
"Sure. There is an overload of Enumerable.Select that takes a Func<TSource, int, TResult> to project an element together with its index:\nFor example:\nchar[] letters = new[] { 'a', 'b', 'c' };\nvar enumerate = letters.Select((c, i) => new { Char = c, Index = i });\nforeach (var result in enumerate) {\n Console.WriteLine(\n String.Format(\"Char = {0}, Index = {1}\", result.Char, result.Index)\n );\n}\n\nOutput:\nChar = a, Index = 0\nChar = b, Index = 1\nChar = c, Index = 2\n\n",
"You can do this with the overload of Enumerable.Select which provides an index variable. This provides access to the index, which you can use to generate a new anonymous type. The following compiles and runs properly:\nstatic void Main()\n{\n\n var letters = new char[] { 'a', 'b', 'c' };\n var results = letters.Select((l, i) => new { Letter = l, Index = i });\n\n foreach (var result in results)\n {\n Console.WriteLine(\"{0} / {1}\", result.Letter, result.Index);\n }\n Console.ReadKey();\n}\n\n"
] |
[
9,
5
] |
[] |
[] |
[
".net",
"linq",
"python"
] |
stackoverflow_0002194684_.net_linq_python.txt
|
Q:
Unit tests in Python
Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good?
A:
Python has several testing frameworks, including unittest, doctest, and nose. The most xUnit-like is unittest, which is documented on Python.org.
unittest documentation
doctest documentation
A:
I recommend nose.
It is the most Pythonic of the unit test frameworks. The test runner runs both doctests and unittests, so you are free to use whatever style of test you like.
A:
There's testoob which is pretty complete suite of test.Also xUnit-ie, and has a nice reporting option
A:
Consider py.test. Not exactly analogous to NUnit, but very good, with nice features including test auto-discovery and a "Watch the tests and code - when something changes rerun the tests that failed last time. As soon as all the tests pass, switch to running all the tests whenever somethings changes." option.
A:
@Greg: PyUnit is included in the standard library as unittest
A:
I recommend Nose.
After the reasonable simple installation, you just have to run "nosetests" in your project folder and Nose will find all your tests and run them. I also like the collection of plugins (coverage, GAE, etc.) and the abilty to call Nose directly from within my Python scripts.
A:
There is also PyUnit which might be what you're looking for.
A:
Never used xUnit, so I can't tell you if the frameworks are good/bad comparativly, but here is a script I wrote which uses the unittest framework (to check the API works as it should), and the doctest (to check the examples I've given work)
My only problem is checking something raises an exception is slightly convoluted (you have to pass it a function/lambda that raises the exception, rather than just the command itself, like the rest of the framework).. Other than that, it does what it should, reliably, and it has been included in the default python distribution for quite some time.
A:
nose seems to be the best combination of flexibility and convenience. It runs unittests, doctests, coverage (with an extension) and py.test-like tests from one framework and does so admirably. It has enough popularity that it has had some IDE integration done as well for Komodo Edit and I wouldn't be surprised to see it elsewhere as well.
I like it for one strong reason: I almost always doctest before writing more extensive tests in another framework. This is because, for basic tests, doctests kill two birds with one stone. You get executable tests (although they are a bit clumsy to write well sometimes) as well as API documentation and interactive documentation at the same time. nose will run these with the bundled doctest extension when you use a command-line option (--with-doctest).
I say this having come from py.test as my former favorite. While it is great, nose tests are similar enough to me that I don't miss it, and I like the integration of the various test methodologies under one roof, so to speak. YMMV, but I recommend taking a good look at nose before choosing another. If you aren't familiar with py.test tests, you should look at them as well. I find them terrific because they are usually written in such a way that they can be easily debugged without the testing framework, which makes one less tricky system involved in the debugging session. I find that alone invaluable, while they are also easier to write than unittest tests in my opinion.
|
Unit tests in Python
|
Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good?
|
[
"Python has several testing frameworks, including unittest, doctest, and nose. The most xUnit-like is unittest, which is documented on Python.org.\n\nunittest documentation\ndoctest documentation\n\n",
"I recommend nose.\nIt is the most Pythonic of the unit test frameworks. The test runner runs both doctests and unittests, so you are free to use whatever style of test you like.\n",
"There's testoob which is pretty complete suite of test.Also xUnit-ie, and has a nice reporting option\n",
"Consider py.test. Not exactly analogous to NUnit, but very good, with nice features including test auto-discovery and a \"Watch the tests and code - when something changes rerun the tests that failed last time. As soon as all the tests pass, switch to running all the tests whenever somethings changes.\" option.\n",
"@Greg: PyUnit is included in the standard library as unittest\n",
"I recommend Nose. \nAfter the reasonable simple installation, you just have to run \"nosetests\" in your project folder and Nose will find all your tests and run them. I also like the collection of plugins (coverage, GAE, etc.) and the abilty to call Nose directly from within my Python scripts. \n",
"There is also PyUnit which might be what you're looking for.\n",
"Never used xUnit, so I can't tell you if the frameworks are good/bad comparativly, but here is a script I wrote which uses the unittest framework (to check the API works as it should), and the doctest (to check the examples I've given work)\nMy only problem is checking something raises an exception is slightly convoluted (you have to pass it a function/lambda that raises the exception, rather than just the command itself, like the rest of the framework).. Other than that, it does what it should, reliably, and it has been included in the default python distribution for quite some time.\n",
"nose seems to be the best combination of flexibility and convenience. It runs unittests, doctests, coverage (with an extension) and py.test-like tests from one framework and does so admirably. It has enough popularity that it has had some IDE integration done as well for Komodo Edit and I wouldn't be surprised to see it elsewhere as well.\nI like it for one strong reason: I almost always doctest before writing more extensive tests in another framework. This is because, for basic tests, doctests kill two birds with one stone. You get executable tests (although they are a bit clumsy to write well sometimes) as well as API documentation and interactive documentation at the same time. nose will run these with the bundled doctest extension when you use a command-line option (--with-doctest).\nI say this having come from py.test as my former favorite. While it is great, nose tests are similar enough to me that I don't miss it, and I like the integration of the various test methodologies under one roof, so to speak. YMMV, but I recommend taking a good look at nose before choosing another. If you aren't familiar with py.test tests, you should look at them as well. I find them terrific because they are usually written in such a way that they can be easily debugged without the testing framework, which makes one less tricky system involved in the debugging session. I find that alone invaluable, while they are also easier to write than unittest tests in my opinion.\n"
] |
[
25,
9,
3,
3,
2,
1,
0,
0,
0
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0000036647_python_unit_testing.txt
|
Q:
How to swap the QGraphicsScene from a QGraphicsView?
QGraphicsView is often hooked up to a QGraphicsScene. What if I want to swap that QGraphicsScene for a new one? How can I accomplish this? Doing it right now is just drawing over the old one.
A:
To swap the scene just call your view's setScene() again with a different QGraphicsScene object.
|
How to swap the QGraphicsScene from a QGraphicsView?
|
QGraphicsView is often hooked up to a QGraphicsScene. What if I want to swap that QGraphicsScene for a new one? How can I accomplish this? Doing it right now is just drawing over the old one.
|
[
"To swap the scene just call your view's setScene() again with a different QGraphicsScene object.\n"
] |
[
0
] |
[] |
[] |
[
"pyqt",
"python"
] |
stackoverflow_0002194829_pyqt_python.txt
|
Q:
setting script path in a buildout using one of the distutils recipes
I am using buildout. I am using it to install openerp. I would like the scripts that openerp creates to run itself available in ${buildout:location}/bin
I tried zerokspot.recipe.distutils and collective.recipe.distutils
How would I get the scripts built in bin?
A:
After some help and some research, it seems that openerp is hardly a standard distutils package. After some research and some help, I tracked down
http://pypi.python.org/pypi/cns.recipe.symlink/0.1
Which I shall use to link the executables to the buildout. This will suffice.
A:
Did you successfuly installed openerp with buildout ?
On my side it just cannot find these modules, but they are in my eggs dir:
Error: python module psycopg2 (PostgreSQL module) is required
Error: python module libxslt (libxslt python bindings) is required
Error: python module pychart (pychart module) is required
Error: python module pydot (pydot module) is required
error: Setup script exited with 1
An error occured when trying to install openerp-server 5.0.0-3. Look above this message for any errors that were output by easy_install.
Is this possible that openerp hardcoded the his searching path somewhere ?
My buildout.cfg look like this:
[buildout]
parts = eggs
versions=versions
newest = false
extensions = lovely.buildouthttp
unzip = true
find-links =
http://download.gna.org/pychart/
[versions]
[eggs]
recipe = zc.recipe.egg
interpreter = python
eggs =
Paste
PasteScript
PasteDeploy
psycopg2
PyChart
pydot
openerp-server
|
setting script path in a buildout using one of the distutils recipes
|
I am using buildout. I am using it to install openerp. I would like the scripts that openerp creates to run itself available in ${buildout:location}/bin
I tried zerokspot.recipe.distutils and collective.recipe.distutils
How would I get the scripts built in bin?
|
[
"After some help and some research, it seems that openerp is hardly a standard distutils package. After some research and some help, I tracked down \nhttp://pypi.python.org/pypi/cns.recipe.symlink/0.1\nWhich I shall use to link the executables to the buildout. This will suffice. \n",
"Did you successfuly installed openerp with buildout ?\nOn my side it just cannot find these modules, but they are in my eggs dir: \nError: python module psycopg2 (PostgreSQL module) is required\nError: python module libxslt (libxslt python bindings) is required\nError: python module pychart (pychart module) is required\nError: python module pydot (pydot module) is required\nerror: Setup script exited with 1\nAn error occured when trying to install openerp-server 5.0.0-3. Look above this message for any errors that were output by easy_install.\n\nIs this possible that openerp hardcoded the his searching path somewhere ?\nMy buildout.cfg look like this:\n[buildout]\nparts = eggs\nversions=versions\nnewest = false\nextensions = lovely.buildouthttp\nunzip = true\nfind-links =\n http://download.gna.org/pychart/\n[versions]\n\n[eggs]\nrecipe = zc.recipe.egg\ninterpreter = python\neggs =\n Paste\n PasteScript\n PasteDeploy\n psycopg2\n PyChart\n pydot\n openerp-server\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"buildout",
"distutils",
"python"
] |
stackoverflow_0002031650_buildout_distutils_python.txt
|
Q:
how to get to various attributes in the same order in python
I have a file of lines and this in turn saves information, speed, timing and type of surfaces for each line. I want to do is sort this information in a np.array in the order shown below where the id is the number of the line.
(id) 0 1 2 3 4 5 6 7 8 9
0 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
1 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
2 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
3 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
4 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
5 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
...
thanks for any response
A:
Your may find numpy.loadtxt useful.
For example, suppose you have a file with these contents:
datafile:
(id) 0 1
0 1 smooth
1 11 choppy
2 20 turbulent
3 2 smooth
4 5 choppy
5 7 bumpy
Then you can load the data into a numpy structured array with
import numpy as np
arr=np.loadtxt('datafile',
dtype=[('id','int'),('speed','float'),('surface','|S20')],
skiprows=1)
Notice you can skip the first line of the datafile by specifying skiprows=1.
Then you can access rows as usual with numeric indices, such as arr[1],
and you can access columns by names, such as arr['speed'].
And you can get the speed in the 3rd row with arr[3]['speed'] or arr['speed'][3].
For more info on structured arrays, see
http://docs.scipy.org/doc/numpy/user/basics.rec.html
A:
Maybe this will get you started...
data ='''
(id) 0 1 2 3 4 5 6 7 8 9
0 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
1 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
2 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
3 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
4 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
5 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10'''
for line in data.strip().split('\n'):
line = line.strip()
if line:
print '*'.join(line.split())
output:
(id)*0*1*2*3*4*5*6*7*8*9
0*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
1*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
2*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
3*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
4*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
5*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10
|
how to get to various attributes in the same order in python
|
I have a file of lines and this in turn saves information, speed, timing and type of surfaces for each line. I want to do is sort this information in a np.array in the order shown below where the id is the number of the line.
(id) 0 1 2 3 4 5 6 7 8 9
0 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
1 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
2 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
3 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
4 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
5 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
...
thanks for any response
|
[
"Your may find numpy.loadtxt useful.\nFor example, suppose you have a file with these contents:\ndatafile:\n(id) 0 1 \n0 1 smooth \n1 11 choppy\n2 20 turbulent\n3 2 smooth\n4 5 choppy\n5 7 bumpy\n\nThen you can load the data into a numpy structured array with\nimport numpy as np\narr=np.loadtxt('datafile',\n dtype=[('id','int'),('speed','float'),('surface','|S20')], \n skiprows=1)\n\nNotice you can skip the first line of the datafile by specifying skiprows=1.\nThen you can access rows as usual with numeric indices, such as arr[1],\nand you can access columns by names, such as arr['speed'].\nAnd you can get the speed in the 3rd row with arr[3]['speed'] or arr['speed'][3].\nFor more info on structured arrays, see \nhttp://docs.scipy.org/doc/numpy/user/basics.rec.html\n",
"Maybe this will get you started...\ndata ='''\n(id) 0 1 2 3 4 5 6 7 8 9\n\n0 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10\n\n1 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 \n\n2 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 \n\n3 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 \n\n4 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 \n\n5 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10'''\n\nfor line in data.strip().split('\\n'):\n line = line.strip()\n if line:\n print '*'.join(line.split())\n\noutput:\n(id)*0*1*2*3*4*5*6*7*8*9\n0*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10\n1*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10\n2*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10\n3*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10\n4*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10\n5*t1*t2*t3*t4*t5*t6*t7*t8*t9*t10\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0002194357_numpy_python.txt
|
Q:
Linux development/minimal smtp and pop3 server
I use python based as well as rails applications on ubuntu linux. We have functionalities like register, forgot password, reset password, email alerts etc features based on emails. Since now a days, we go on offline development, we want to run a local smtp & pop3 server to send and receive emails.
Emails shall be send via the our web application and we will use the email clients like thunderbird to receive emails(just to verify).
I have used jmailsrv (I have used 6 years ago, but could not locate exact package now), a java based simple email server. Are there any other light alternative for development work?
A:
Why does it need to be a simple mail server?
Can't you just use something like postfix which is very easy for simple configurations
|
Linux development/minimal smtp and pop3 server
|
I use python based as well as rails applications on ubuntu linux. We have functionalities like register, forgot password, reset password, email alerts etc features based on emails. Since now a days, we go on offline development, we want to run a local smtp & pop3 server to send and receive emails.
Emails shall be send via the our web application and we will use the email clients like thunderbird to receive emails(just to verify).
I have used jmailsrv (I have used 6 years ago, but could not locate exact package now), a java based simple email server. Are there any other light alternative for development work?
|
[
"Why does it need to be a simple mail server?\nCan't you just use something like postfix which is very easy for simple configurations\n"
] |
[
2
] |
[] |
[] |
[
"email",
"linux",
"python",
"ruby_on_rails"
] |
stackoverflow_0002195203_email_linux_python_ruby_on_rails.txt
|
Q:
Determining the unmatched portion of a string using a regex in Python
Suppose I have a string "a foobar" and I use "^a\s*" to match "a ".
Is there a way to easily get "foobar" returned? (What was NOT matched)
I want to use a regex to look for a command word and also use the regex to remove the command word from the string.
I know how to do this using something like:
mystring[:regexobj.start()] + email[regexobj.end():]
But this falls apart if I have multiple matches.
Thanks!
A:
Use re.sub:
import re
s = "87 foo 87 bar"
r = re.compile(r"87\s*")
s = r.sub('', s)
print s
Result:
foo bar
A:
from http://docs.python.org/library/re.html#re.split
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
so your example would be
>>> re.split(r'(^a\s*)', "a foobar")
['', 'a ', 'foobar']
at which point you can separate the odd items (your match) from the even items (the rest).
>>> l = re.split(r'(^a\s*)', "a foobar")
>>> l[1::2] # matching strings
['a ']
>>> l[::2] # non-matching strings
['', 'foobar']
This has the advantage over re.sub in that you can tell, when, where, and how many matches were found.
A:
>>> import re
>>> re.sub("87\s*", "", "87 foo 87 bar")
'foo bar'
A:
Instead of splitting or separating, maybe you can use re.sub and substitute a blank, empty string ("") whenever you find the pattern. For example...
>>> import re
>>> re.sub("^a\s*", "","a foobar")
'foobar''
>>> re.sub("a\s*", "","a foobar a foobar")
'foobr foobr'
>>> re.sub("87\s*", "","87 foo 87 bar")
'foo bar'
|
Determining the unmatched portion of a string using a regex in Python
|
Suppose I have a string "a foobar" and I use "^a\s*" to match "a ".
Is there a way to easily get "foobar" returned? (What was NOT matched)
I want to use a regex to look for a command word and also use the regex to remove the command word from the string.
I know how to do this using something like:
mystring[:regexobj.start()] + email[regexobj.end():]
But this falls apart if I have multiple matches.
Thanks!
|
[
"Use re.sub:\nimport re\ns = \"87 foo 87 bar\"\nr = re.compile(r\"87\\s*\")\ns = r.sub('', s)\nprint s\n\nResult:\nfoo bar\n\n",
"from http://docs.python.org/library/re.html#re.split\n>>> re.split('(\\W+)', 'Words, words, words.')\n['Words', ', ', 'words', ', ', 'words', '.', '']\n\nso your example would be\n>>> re.split(r'(^a\\s*)', \"a foobar\")\n['', 'a ', 'foobar']\n\nat which point you can separate the odd items (your match) from the even items (the rest).\n>>> l = re.split(r'(^a\\s*)', \"a foobar\")\n>>> l[1::2] # matching strings\n['a ']\n>>> l[::2] # non-matching strings\n['', 'foobar']\n\nThis has the advantage over re.sub in that you can tell, when, where, and how many matches were found.\n",
">>> import re\n>>> re.sub(\"87\\s*\", \"\", \"87 foo 87 bar\")\n'foo bar'\n\n",
"Instead of splitting or separating, maybe you can use re.sub and substitute a blank, empty string (\"\") whenever you find the pattern. For example...\n>>> import re\n>>> re.sub(\"^a\\s*\", \"\",\"a foobar\")\n'foobar''\n>>> re.sub(\"a\\s*\", \"\",\"a foobar a foobar\")\n'foobr foobr'\n>>> re.sub(\"87\\s*\", \"\",\"87 foo 87 bar\")\n'foo bar'\n\n"
] |
[
8,
2,
1,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002195340_python_regex.txt
|
Q:
how do I know if a remote user is connected in django?
how do I know if a remote user is connected in django?, like gmail chat, or facebook chat... I need that in the templates system. Sorry for my english
A:
If you need just a general idea of who is currently visiting your website, which includes anonymous visitors, use django-tracking app.
If you need a chat application, or need to know exactly who is logged in at any time, this is much more complicated and will require you to know a lot about chat protocols like XMPP and how to use persistent connections with ajax or comet methods. Some starting projects to look at: xmpp-psn and django-xmpp
Also see this web page for a list of non-Django XMPP browser clients: http://xmpp.org/software/clients.shtml
A:
Comet is probably what you want. Look at Orbited, Hurricane or Tornado.
|
how do I know if a remote user is connected in django?
|
how do I know if a remote user is connected in django?, like gmail chat, or facebook chat... I need that in the templates system. Sorry for my english
|
[
"If you need just a general idea of who is currently visiting your website, which includes anonymous visitors, use django-tracking app.\nIf you need a chat application, or need to know exactly who is logged in at any time, this is much more complicated and will require you to know a lot about chat protocols like XMPP and how to use persistent connections with ajax or comet methods. Some starting projects to look at: xmpp-psn and django-xmpp\nAlso see this web page for a list of non-Django XMPP browser clients: http://xmpp.org/software/clients.shtml\n",
"Comet is probably what you want. Look at Orbited, Hurricane or Tornado.\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"django_templates",
"programming_languages",
"python"
] |
stackoverflow_0002195386_django_django_templates_programming_languages_python.txt
|
Q:
Override all operators in python
I have a wrapper class for an object. I want it to apply all operations applied to it on the wrapped object, e.g wrapper+=a would yield the same result as wrapped+=a, for instance. I want to apply this for all operators. Any simple way to override all operators without overriding each one explicitly?
A:
ActiveState Code: Recipe 496741: Object Proxying
A:
No, sorry. Though you could write an interface (probably as a decorator or base class) that makes this easy, if you need to do it more than once. Or use one provided already. (Guess I was 40s too late.)
|
Override all operators in python
|
I have a wrapper class for an object. I want it to apply all operations applied to it on the wrapped object, e.g wrapper+=a would yield the same result as wrapped+=a, for instance. I want to apply this for all operators. Any simple way to override all operators without overriding each one explicitly?
|
[
"ActiveState Code: Recipe 496741: Object Proxying\n",
"No, sorry. Though you could write an interface (probably as a decorator or base class) that makes this easy, if you need to do it more than once. Or use one provided already. (Guess I was 40s too late.)\n"
] |
[
6,
1
] |
[] |
[] |
[
"operators",
"overriding",
"python"
] |
stackoverflow_0002195601_operators_overriding_python.txt
|
Q:
How do I write a Django template custom tag that adds a slash before a single quote?
Am I doing this right? (probably not...someone correct? thanks)
@register.filter('addslashes')
@stringfilter
def addslashes(text, arg):
return text.replace('\'','\\'')
{{ query|addslashes }}
A:
There is a builtin filter with the exact same name: addslashes
It also escapes double quotes, and double slashes. If you only want single quotes, you will have to adapt it and name it differently.
Here is how the original works:
def addslashes(value):
"""
Adds slashes before quotes. Useful for escaping strings in CSV, for
example. Less useful for escaping JavaScript; use the ``escapejs``
filter instead.
"""
return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
addslashes.is_safe = True
addslashes = stringfilter(addslashes)
|
How do I write a Django template custom tag that adds a slash before a single quote?
|
Am I doing this right? (probably not...someone correct? thanks)
@register.filter('addslashes')
@stringfilter
def addslashes(text, arg):
return text.replace('\'','\\'')
{{ query|addslashes }}
|
[
"There is a builtin filter with the exact same name: addslashes\nIt also escapes double quotes, and double slashes. If you only want single quotes, you will have to adapt it and name it differently.\nHere is how the original works:\ndef addslashes(value):\n \"\"\"\n Adds slashes before quotes. Useful for escaping strings in CSV, for\n example. Less useful for escaping JavaScript; use the ``escapejs``\n filter instead.\n \"\"\"\n return value.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\")\naddslashes.is_safe = True\naddslashes = stringfilter(addslashes)\n\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python",
"templates"
] |
stackoverflow_0002195588_django_python_templates.txt
|
Q:
How do I do "or" in Django template code?
{% if is_loggedin OR is_anonymous %}
test message
{% endif %}
A:
{% if is_loggedin or is_anonymous %}
test message
{% endif %}
Like that.
A:
if tags may use and, or or not to test a number of variables or to negate a given variable:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#if
The way you're doing it is fine. :-)
|
How do I do "or" in Django template code?
|
{% if is_loggedin OR is_anonymous %}
test message
{% endif %}
|
[
"{% if is_loggedin or is_anonymous %}\ntest message\n{% endif %}\n\nLike that.\n",
"\nif tags may use and, or or not to test a number of variables or to negate a given variable:\n\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#if\nThe way you're doing it is fine. :-)\n"
] |
[
4,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002195726_django_python.txt
|
Q:
Python conversion to ISO-8859-5
I'm facing problems when trying to convert a UTF-8 file (containing Russian characters) into an ISO-8859-5 file: 'charmap' codec can't encode character u'\ufeff' in position 0: character maps to . Has anyone got an idea of what's wrong(?) given the following:
def convert():
try:
import codecs
data = codecs.open('in.txt', 'r', 'utf-8').read()
except Exception, e:
print e
sys.exit(1)
f = open('out.txt', 'w')
try:
f.write(data.encode('iso-8859-5'))
except Exception, e:
print e
finally:
f.close()
"in.txt":
ё!—№%«»(эюпоиуыяафйклж;нцхз
A:
feff is a Byte-Order-Mark character. ISO-8859-5 won't have any representation for it.
You'll need to strip it off your data variable before encoding it into ISO-8859-5.
A:
Recent versions of Python have the utf-8-sig codec that will automatically strip the BOM off a UTF-8-encoded string or file when reading it:
>>> print '\xef\xbb\xbf\xe3\x81\x82'.decode('utf-8-sig')
あ
|
Python conversion to ISO-8859-5
|
I'm facing problems when trying to convert a UTF-8 file (containing Russian characters) into an ISO-8859-5 file: 'charmap' codec can't encode character u'\ufeff' in position 0: character maps to . Has anyone got an idea of what's wrong(?) given the following:
def convert():
try:
import codecs
data = codecs.open('in.txt', 'r', 'utf-8').read()
except Exception, e:
print e
sys.exit(1)
f = open('out.txt', 'w')
try:
f.write(data.encode('iso-8859-5'))
except Exception, e:
print e
finally:
f.close()
"in.txt":
ё!—№%«»(эюпоиуыяафйклж;нцхз
|
[
"feff is a Byte-Order-Mark character. ISO-8859-5 won't have any representation for it.\nYou'll need to strip it off your data variable before encoding it into ISO-8859-5.\n",
"Recent versions of Python have the utf-8-sig codec that will automatically strip the BOM off a UTF-8-encoded string or file when reading it:\n>>> print '\\xef\\xbb\\xbf\\xe3\\x81\\x82'.decode('utf-8-sig')\nあ\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"character_encoding",
"encoding",
"python",
"unicode"
] |
stackoverflow_0002193611_character_encoding_encoding_python_unicode.txt
|
Q:
Why isn't there a do while flow control statement in python?
Is there a good reason why there isn't a do while flow control statement in python?
Why do people have to write while and break explicitly?
A:
It has been proposed in PEP 315 but hasn't been implemented because nobody has come up with a syntax that's clearer than the while True with an inner if-break.
A:
Probably because Guido didn't think it was necessary. There are a bunch of different flow-control statements you could support, but most of them are variants of each other. Frankly, I've found the do-while statement to be one of the less useful ones.
A:
Because then you would have two ways to do something.
A:
Python adds features only when they significantly simplify some code.
while True:
...
if not cond: break
is not less simple than a do-while loop, for which there is no obvious natural python syntax anyway.
do:
...
while cond
(Looks weird)
or this?
do:
...
while cond
(The while looks like a regular while statement)
|
Why isn't there a do while flow control statement in python?
|
Is there a good reason why there isn't a do while flow control statement in python?
Why do people have to write while and break explicitly?
|
[
"It has been proposed in PEP 315 but hasn't been implemented because nobody has come up with a syntax that's clearer than the while True with an inner if-break.\n",
"Probably because Guido didn't think it was necessary. There are a bunch of different flow-control statements you could support, but most of them are variants of each other. Frankly, I've found the do-while statement to be one of the less useful ones.\n",
"Because then you would have two ways to do something.\n",
"Python adds features only when they significantly simplify some code.\nwhile True:\n ...\n if not cond: break\n\nis not less simple than a do-while loop, for which there is no obvious natural python syntax anyway.\ndo:\n ...\n while cond\n\n(Looks weird)\nor this?\ndo:\n ...\nwhile cond\n\n(The while looks like a regular while statement)\n"
] |
[
11,
10,
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002192344_python.txt
|
Q:
Python class has method "set", how to reference builtin set type?
If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in an _____exit_____ function.
A:
I think I know what's going on here. Are you doing something like this?
>>> class A(object):
... def set(self):
... pass
... def test(self, x=set):
... return x
...
>>> set
<type 'set'>
>>> A().test()
<function set at 0x64270>
This is a subtle problem due to the way methods are defined in classes. It is what allows you to make method aliases so easily, e.g.,
class A(object):
def some_method(self):
pass
some_other_method = some_method
You can either put set at the bottom of your class definition, or you can refer to the builtin set using __builtins__.set.
A:
Object attributes are always accessed via a reference, so there is no way for an object attribute to shadow a builtin.
A:
Usually method names are disambiguated from global names because you have to prefix self..
So self.set() invokes your class method and set() invokes the global set.
If this doesn't help, perhaps post the code you're having trouble with.
A:
You can refer to built-in set as __builtins__.set.
A:
If you run the code below you will notice that the set method of the UsesSet class does not obscure the built-in set type.
class UsesSet(object):
def set(self):
pass
def other(self):
my_set = set([1, 2])
print type(my_set), my_set
obj = UsesSet()
obj.other()
The code above outputs <type 'set'> set([1, 2]) showing that the set() method of our class has not hidden the built-in set()
If however you have module in which you have defined a function named set like below something different happens:
def set(arg):
print "This is my own set function"
class UsesSet(object):
def other(self):
my_set = set([1, 2])
print type(my_set), my_set
obj = UsesSet()
obj.other()
The code above outputs:
This is my own set function
<type 'NoneType'> None
So as you can see a module level function with the same name as a built-in hides the built-in.
|
Python class has method "set", how to reference builtin set type?
|
If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in an _____exit_____ function.
|
[
"I think I know what's going on here. Are you doing something like this?\n>>> class A(object):\n... def set(self):\n... pass\n... def test(self, x=set):\n... return x\n... \n>>> set\n<type 'set'>\n>>> A().test()\n<function set at 0x64270>\n\nThis is a subtle problem due to the way methods are defined in classes. It is what allows you to make method aliases so easily, e.g.,\nclass A(object):\n def some_method(self):\n pass\n some_other_method = some_method\n\nYou can either put set at the bottom of your class definition, or you can refer to the builtin set using __builtins__.set.\n",
"Object attributes are always accessed via a reference, so there is no way for an object attribute to shadow a builtin.\n",
"Usually method names are disambiguated from global names because you have to prefix self..\nSo self.set() invokes your class method and set() invokes the global set.\nIf this doesn't help, perhaps post the code you're having trouble with.\n",
"You can refer to built-in set as __builtins__.set.\n",
"If you run the code below you will notice that the set method of the UsesSet class does not obscure the built-in set type.\nclass UsesSet(object):\n def set(self):\n pass\n def other(self):\n my_set = set([1, 2])\n print type(my_set), my_set\n\nobj = UsesSet()\nobj.other()\n\nThe code above outputs <type 'set'> set([1, 2]) showing that the set() method of our class has not hidden the built-in set()\nIf however you have module in which you have defined a function named set like below something different happens:\ndef set(arg):\n print \"This is my own set function\"\n\nclass UsesSet(object):\n def other(self):\n my_set = set([1, 2])\n print type(my_set), my_set\n\nobj = UsesSet()\nobj.other()\n\nThe code above outputs:\nThis is my own set function\n<type 'NoneType'> None\n\nSo as you can see a module level function with the same name as a built-in hides the built-in.\n"
] |
[
10,
3,
2,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002195755_python.txt
|
Q:
django csv import threading
Is it possible to use threading when importing data from csv files to django.
A:
Django is Python, so yeah you can use threads, processing etc. Look at python docs on this matter.
But, spawning threads in web environment might be not be such a good idea, try searching here for "django asynchronous" - you'll get many ideas of how to this without threading.
|
django csv import threading
|
Is it possible to use threading when importing data from csv files to django.
|
[
"Django is Python, so yeah you can use threads, processing etc. Look at python docs on this matter.\nBut, spawning threads in web environment might be not be such a good idea, try searching here for \"django asynchronous\" - you'll get many ideas of how to this without threading.\n"
] |
[
2
] |
[] |
[] |
[
"csv",
"django",
"multithreading",
"python"
] |
stackoverflow_0002190075_csv_django_multithreading_python.txt
|
Q:
VLC/Python bindings?
Does anyone know how to implement the VLC Python bindings? I downloaded vlc.py and vlcwidget.py from the VLC wiki (http://wiki.videolan.org/Python_bindings) and tried to run vlcwidget. Other than having vlc installed, do I need to do anything else, or should I just be able to run 'python vlcwidget.py '? Because that is not working for me. I'm using Python2.5 and VLC 0.8.6e on Ubuntu 8.04.
The problem has to do with my libvlc shared library, I think. That library is used to create this instance:
dll=ctypes.CDLL('libvlc.so')
and then later, the error occurs here:
if hasattr(dll, 'libvlc_media_player_new'): ...
dll apparently doesn't have a libvlc_media_player_new attribute and so fails to create other objects it needs. Specifically, the libvlc_media_player_new function isn't created.
A:
$ git clone git://git.videolan.org/vlc.git && cd vlc
$ git log -Slibvlc_media_player_new
...
commit bf1292e44390c6469483cea3817d6c2a3dbd811c
Author: Pierre d'Herbemont <pdherbemont@videolan.org>
Date: Sun Mar 30 03:59:32 2008 +0200
libvlc: rename libvlc_media_descriptor to libvlc_media and libvlc_media_instance to libvlc_media_player.
There was no libvlc_media_player_new prior to this commit, which went in some time between 0.8.4 and 0.9. (I'm not sure when; VLC's git repository seems to be missing tags in that range.)
The Python bindings use the newer API. You'll have to upgrade VLC to use them.
|
VLC/Python bindings?
|
Does anyone know how to implement the VLC Python bindings? I downloaded vlc.py and vlcwidget.py from the VLC wiki (http://wiki.videolan.org/Python_bindings) and tried to run vlcwidget. Other than having vlc installed, do I need to do anything else, or should I just be able to run 'python vlcwidget.py '? Because that is not working for me. I'm using Python2.5 and VLC 0.8.6e on Ubuntu 8.04.
The problem has to do with my libvlc shared library, I think. That library is used to create this instance:
dll=ctypes.CDLL('libvlc.so')
and then later, the error occurs here:
if hasattr(dll, 'libvlc_media_player_new'): ...
dll apparently doesn't have a libvlc_media_player_new attribute and so fails to create other objects it needs. Specifically, the libvlc_media_player_new function isn't created.
|
[
"\n$ git clone git://git.videolan.org/vlc.git && cd vlc\n$ git log -Slibvlc_media_player_new\n...\ncommit bf1292e44390c6469483cea3817d6c2a3dbd811c\nAuthor: Pierre d'Herbemont <pdherbemont@videolan.org>\nDate: Sun Mar 30 03:59:32 2008 +0200\n\n libvlc: rename libvlc_media_descriptor to libvlc_media and libvlc_media_instance to libvlc_media_player.\n\nThere was no libvlc_media_player_new prior to this commit, which went in some time between 0.8.4 and 0.9. (I'm not sure when; VLC's git repository seems to be missing tags in that range.)\nThe Python bindings use the newer API. You'll have to upgrade VLC to use them.\n"
] |
[
2
] |
[] |
[] |
[
"binding",
"libvlc",
"python",
"vlc"
] |
stackoverflow_0002195631_binding_libvlc_python_vlc.txt
|
Q:
Saving an image of what a device context drew, wxPython
I need to be able to save an image (format doesn't matter) of the state of the device context canvas. I tried dc.GetAsBitmap but it returns invalid bitmaps. How can I do it?
A:
I believe this should do the trick:
def saveSnapshot(dcSource):
# based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08
size = dcSource.Size
# Create a Bitmap that will later on hold the screenshot image
# Note that the Bitmap must have a size big enough to hold the screenshot
# -1 means using the current default colour depth
bmp = wx.EmptyBitmap(size.width, size.height)
# Create a memory DC that will be used for actually taking the screenshot
memDC = wx.MemoryDC()
# Tell the memory DC to use our Bitmap
# all drawing action on the memory DC will go to the Bitmap now
memDC.SelectObject(bmp)
# Blit (in this case copy) the actual screen on the memory DC
# and thus the Bitmap
memDC.Blit( 0, # Copy to this X coordinate
0, # Copy to this Y coordinate
size.width, # Copy this width
size.height, # Copy this height
dcSource, # From where do we copy?
0, # What's the X offset in the original DC?
0 # What's the Y offset in the original DC?
)
# Select the Bitmap out of the memory DC by selecting a new
# uninitialized Bitmap
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
img.SaveFile('saved.png', wx.BITMAP_TYPE_PNG)
(I'd just include a link to the original but couldn't find it quickly.)
A:
Yo can probably figure something out of this (working with images and wxPython)
|
Saving an image of what a device context drew, wxPython
|
I need to be able to save an image (format doesn't matter) of the state of the device context canvas. I tried dc.GetAsBitmap but it returns invalid bitmaps. How can I do it?
|
[
"I believe this should do the trick:\ndef saveSnapshot(dcSource):\n # based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08\n size = dcSource.Size\n\n # Create a Bitmap that will later on hold the screenshot image\n # Note that the Bitmap must have a size big enough to hold the screenshot\n # -1 means using the current default colour depth\n bmp = wx.EmptyBitmap(size.width, size.height)\n\n # Create a memory DC that will be used for actually taking the screenshot\n memDC = wx.MemoryDC()\n\n # Tell the memory DC to use our Bitmap\n # all drawing action on the memory DC will go to the Bitmap now\n memDC.SelectObject(bmp)\n\n # Blit (in this case copy) the actual screen on the memory DC\n # and thus the Bitmap\n memDC.Blit( 0, # Copy to this X coordinate\n 0, # Copy to this Y coordinate\n size.width, # Copy this width\n size.height, # Copy this height\n dcSource, # From where do we copy?\n 0, # What's the X offset in the original DC?\n 0 # What's the Y offset in the original DC?\n )\n\n # Select the Bitmap out of the memory DC by selecting a new\n # uninitialized Bitmap\n memDC.SelectObject(wx.NullBitmap)\n\n img = bmp.ConvertToImage()\n img.SaveFile('saved.png', wx.BITMAP_TYPE_PNG)\n\n(I'd just include a link to the original but couldn't find it quickly.)\n",
"Yo can probably figure something out of this (working with images and wxPython)\n"
] |
[
6,
1
] |
[] |
[] |
[
"python",
"wxpython",
"wxwidgets"
] |
stackoverflow_0002195792_python_wxpython_wxwidgets.txt
|
Q:
Does PySVN need Subversion installed?
I have python script that uses pysvn and checks out or updates a local copy obtained also from a local repo.
client.checkout(url,
path,
revision=pysvn.Revision(pysvn.opt_revision_kind.number, RevNumber),
ignore_externals=False)
I am running this on a windows machine in which I haven't installed subversion. The svnsync used to obtain a copy of an actual repo was done on another machine.
With this, I assumed that PySVN doesn't need SVN installed to be able to checkout or update from a folder that contains the result of svnsync.
Problems start when In Windows some repos have files with lowercase and mixedcase versions. Windows will give an error when updating or creating two files with different case, so I jumped into Ubuntu to run my script.
In Ubuntu, I get this error running my script with pysvn:
pysvn._pysvn_2_6.ClientError: Unable to open an ra_local session to URL
Unable to open repository xxxx
Expected FS format between '1' and '3'; found '4'
After some searching, this seems to be an error message related to svn 1.6 but pysvn supposedly supports that and sudo apt-get install python-svn tells me I have the latest version...
So, is this because of SVN or pySVN? If the windows pysvn doesn't complain about it, why does the Ubuntu one do? Or is it tied to having svn on the machine or not?
Figuring this one out will help me towards answering a previous post of mine essentially on the same topic
A:
This is because your Ubuntu is accessing the repo with too old a version of the SVN API.
The windows one is fine because it is obviously using a newer version.
According the PySVN download page:
Windows binary kits
Note: These windows kits are all you
need. It is not necessary to install
any Subversion kits.
and
Mac OS X binary kits
Note: These Mac OS X kits are all you
need. It is not necessary to install
any Subversion kits.
but, come
Linux binary kits
it doesn't mention anything about NOT needing Subversion. My guess is the PySVN linux needs subversion and hence is only using 1.5.x
In addition to this, it only says
built against Subversion 1.5.6 and
Subversion 1.6.5
for Windows and Mac OSX, not for Linux
You will need to install an SVN Client on Ubuntu that supports the newer repo format. Obviously you could wait until the Nix version of PySVN is updated, or find another SVN tool...
|
Does PySVN need Subversion installed?
|
I have python script that uses pysvn and checks out or updates a local copy obtained also from a local repo.
client.checkout(url,
path,
revision=pysvn.Revision(pysvn.opt_revision_kind.number, RevNumber),
ignore_externals=False)
I am running this on a windows machine in which I haven't installed subversion. The svnsync used to obtain a copy of an actual repo was done on another machine.
With this, I assumed that PySVN doesn't need SVN installed to be able to checkout or update from a folder that contains the result of svnsync.
Problems start when In Windows some repos have files with lowercase and mixedcase versions. Windows will give an error when updating or creating two files with different case, so I jumped into Ubuntu to run my script.
In Ubuntu, I get this error running my script with pysvn:
pysvn._pysvn_2_6.ClientError: Unable to open an ra_local session to URL
Unable to open repository xxxx
Expected FS format between '1' and '3'; found '4'
After some searching, this seems to be an error message related to svn 1.6 but pysvn supposedly supports that and sudo apt-get install python-svn tells me I have the latest version...
So, is this because of SVN or pySVN? If the windows pysvn doesn't complain about it, why does the Ubuntu one do? Or is it tied to having svn on the machine or not?
Figuring this one out will help me towards answering a previous post of mine essentially on the same topic
|
[
"This is because your Ubuntu is accessing the repo with too old a version of the SVN API.\nThe windows one is fine because it is obviously using a newer version.\nAccording the PySVN download page:\n\nWindows binary kits\nNote: These windows kits are all you\n need. It is not necessary to install\n any Subversion kits.\n\nand\n\nMac OS X binary kits\nNote: These Mac OS X kits are all you\n need. It is not necessary to install\n any Subversion kits.\n\nbut, come \n\nLinux binary kits\n\nit doesn't mention anything about NOT needing Subversion. My guess is the PySVN linux needs subversion and hence is only using 1.5.x\nIn addition to this, it only says \n\nbuilt against Subversion 1.5.6 and\n Subversion 1.6.5\n\nfor Windows and Mac OSX, not for Linux\nYou will need to install an SVN Client on Ubuntu that supports the newer repo format. Obviously you could wait until the Nix version of PySVN is updated, or find another SVN tool...\n"
] |
[
1
] |
[] |
[] |
[
"pysvn",
"python",
"svn",
"ubuntu_9.04",
"windows"
] |
stackoverflow_0002197156_pysvn_python_svn_ubuntu_9.04_windows.txt
|
Q:
Python shelve OutOfMemory error
I have some data stored in a DB that I want to process. DB access is painfully slow, so I decided to load all data in a dictionary before any processing. However, due to the huge size of the data stored, I get an out of memory error (I see more than 2 gigs being used). So I decided to use a disk data structure, and found out that using shelve is an option. Here's what I do (pseudo python code)
def loadData():
if (#dict exists on disk):
d = shelve.open(name)
return d
else:
d = shelve.open(name, writeback=True)
#access DB and write data to dict
# d[key] = value
# or for mutable values
# oldValue = d[key]
# newValue = f(oldValue)
# d[key] = newValue
d.close()
d = shelve.open(name, writeback=True)
return d
I have a couple of questions,
1) Do I really need the writeBack=True? What does it do?
2) I still get an OutofMemory exception, since I do not exercise any control over when the data is being written to disk. How do I do that? I tried doing a sync() every few iterations but that didn't help either.
Thanks!
A:
writeback=True forces the shelf to keep in-memory any item ever fetched, and write them back when the shelf is closed. So, it consumes much more memory, and slows down closing.
The advantage of the parameter is that, with it, you don't need the contorted code you show in your comment for mutable items whose mutator is a method -- just
shelf['foobar'].append(23)
works (if shelf was opened with writeback enabled), assuming the item at key 'foobar' is a list of course, while it would silently be a no-operation (leaving the item on disk unchanged) if shelf was opened without writeback -- in the latter case you actually do need to code
thelist = shelf['foobar']
thelist.append(23)
shekf['foobar'] = thelist
in your comment's spirit -- which is stylistically somewhat of a bummer.
However, since you are having memory problems, I definitely recommend not using this dubious writeback option. I think I can call it "dubious" since I was the one proposing and first implementing it, but that was many years ago, and I've mostly repented of doing it -- it generales more confusion (as your Q evidences) than it allows elegance and handiness in moving code originally written to work with dicts (which would use the first idiom, not the second, and thus need rewriting in order to be usable with shelves without traceback). Ah well, sorry, it did seem a good idea at the time.
A:
Using the sqlite3 module is probably your best choice here. You might be able to use sqlite entirely in memory anyway since its memory footprint might be a bit smaller than using python objects anyway. It's generally a better choice than using shelve anyway; shelve uses pickle underneath, which is rarely what you want.
Hell, you could just convert your entire existing database to a sqlite database. sqlite is nice and fast.
|
Python shelve OutOfMemory error
|
I have some data stored in a DB that I want to process. DB access is painfully slow, so I decided to load all data in a dictionary before any processing. However, due to the huge size of the data stored, I get an out of memory error (I see more than 2 gigs being used). So I decided to use a disk data structure, and found out that using shelve is an option. Here's what I do (pseudo python code)
def loadData():
if (#dict exists on disk):
d = shelve.open(name)
return d
else:
d = shelve.open(name, writeback=True)
#access DB and write data to dict
# d[key] = value
# or for mutable values
# oldValue = d[key]
# newValue = f(oldValue)
# d[key] = newValue
d.close()
d = shelve.open(name, writeback=True)
return d
I have a couple of questions,
1) Do I really need the writeBack=True? What does it do?
2) I still get an OutofMemory exception, since I do not exercise any control over when the data is being written to disk. How do I do that? I tried doing a sync() every few iterations but that didn't help either.
Thanks!
|
[
"writeback=True forces the shelf to keep in-memory any item ever fetched, and write them back when the shelf is closed. So, it consumes much more memory, and slows down closing.\nThe advantage of the parameter is that, with it, you don't need the contorted code you show in your comment for mutable items whose mutator is a method -- just\nshelf['foobar'].append(23)\n\nworks (if shelf was opened with writeback enabled), assuming the item at key 'foobar' is a list of course, while it would silently be a no-operation (leaving the item on disk unchanged) if shelf was opened without writeback -- in the latter case you actually do need to code\nthelist = shelf['foobar']\nthelist.append(23)\nshekf['foobar'] = thelist\n\nin your comment's spirit -- which is stylistically somewhat of a bummer.\nHowever, since you are having memory problems, I definitely recommend not using this dubious writeback option. I think I can call it \"dubious\" since I was the one proposing and first implementing it, but that was many years ago, and I've mostly repented of doing it -- it generales more confusion (as your Q evidences) than it allows elegance and handiness in moving code originally written to work with dicts (which would use the first idiom, not the second, and thus need rewriting in order to be usable with shelves without traceback). Ah well, sorry, it did seem a good idea at the time.\n",
"Using the sqlite3 module is probably your best choice here. You might be able to use sqlite entirely in memory anyway since its memory footprint might be a bit smaller than using python objects anyway. It's generally a better choice than using shelve anyway; shelve uses pickle underneath, which is rarely what you want.\nHell, you could just convert your entire existing database to a sqlite database. sqlite is nice and fast.\n"
] |
[
10,
0
] |
[] |
[] |
[
"dictionary",
"out_of_memory",
"persistence",
"python",
"shelve"
] |
stackoverflow_0002196969_dictionary_out_of_memory_persistence_python_shelve.txt
|
Q:
Convert Chrome history date/time stamp to readable format
I originally posted this question looking for an answer with using python, got some good help, but have still not been able to find a solution. I have a script running on OS X 10.5 client machines that captures internet browsing history (required as part of my sys admin duties in a US public school). Firefox 3.x stores history in a sqlite db, and I have figured out how to get that info out using python/sqlite3. Firefox 3.x uses a conventional unixtimestamp to mark visits and that is not difficult to convert... Chrome also stores browser history in a sqlite db, but its timestamp is formatted as the number of microseconds since January, 1601. I'd like to figure this out using python, but as far as I know, the sqlite3 module doesn't support that UTC format. Is there another tool out there to convert Chrome timestamps to a human readable format?
A:
Use the datetime module. For example, if the number of microseconds in questions is 10**16:
>>> datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=1e16)
datetime.datetime(1917, 11, 21, 17, 46, 40)
>>> _.isoformat()
'1917-11-21T17:46:40'
this tells you it was just past a quarter to 6pm of November 21, 1917. You can format datetime objects in any way you want thanks to their strftime method, of course. If you also need to apply timezones (other than the UTC you start with), look at third-party module pytz.
|
Convert Chrome history date/time stamp to readable format
|
I originally posted this question looking for an answer with using python, got some good help, but have still not been able to find a solution. I have a script running on OS X 10.5 client machines that captures internet browsing history (required as part of my sys admin duties in a US public school). Firefox 3.x stores history in a sqlite db, and I have figured out how to get that info out using python/sqlite3. Firefox 3.x uses a conventional unixtimestamp to mark visits and that is not difficult to convert... Chrome also stores browser history in a sqlite db, but its timestamp is formatted as the number of microseconds since January, 1601. I'd like to figure this out using python, but as far as I know, the sqlite3 module doesn't support that UTC format. Is there another tool out there to convert Chrome timestamps to a human readable format?
|
[
"Use the datetime module. For example, if the number of microseconds in questions is 10**16:\n>>> datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=1e16)\ndatetime.datetime(1917, 11, 21, 17, 46, 40)\n>>> _.isoformat()\n'1917-11-21T17:46:40'\n\nthis tells you it was just past a quarter to 6pm of November 21, 1917. You can format datetime objects in any way you want thanks to their strftime method, of course. If you also need to apply timezones (other than the UTC you start with), look at third-party module pytz.\n"
] |
[
9
] |
[] |
[] |
[
"datetime",
"google_chrome",
"macos",
"python"
] |
stackoverflow_0002193820_datetime_google_chrome_macos_python.txt
|
Q:
New to Mac Platform, Trying to get back to default python install
I've been trying to follow this blog post to get my python version back to the snow leopard default. I have followed the first two steps without a problem but am lost when it comes to 3 and 4. I installed Python 2.6.4 but I assume the instructions are pretty similar. Thanks for your help!
A:
Step 3:
sudo rm /usr/local/bin/python
Step 4:
ls ~/.bash_profile.pysave
If the file exists:
rm ~/.bash_profile && mv ~/.bash_profile.pysave ~/.bash_profile
You will probably want to close your shell / Terminal and open a new one at this point. Run Python and see what it tells you.
A:
Please be aware that Snow Leopard ships with a buggy IDLE. You will not be able to create a new document with it. If you will use another editor, it may not bother you. I a working with the following version:
Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
|
New to Mac Platform, Trying to get back to default python install
|
I've been trying to follow this blog post to get my python version back to the snow leopard default. I have followed the first two steps without a problem but am lost when it comes to 3 and 4. I installed Python 2.6.4 but I assume the instructions are pretty similar. Thanks for your help!
|
[
"Step 3:\nsudo rm /usr/local/bin/python\nStep 4:\nls ~/.bash_profile.pysave\nIf the file exists:\nrm ~/.bash_profile && mv ~/.bash_profile.pysave ~/.bash_profile\nYou will probably want to close your shell / Terminal and open a new one at this point. Run Python and see what it tells you.\n",
"Please be aware that Snow Leopard ships with a buggy IDLE. You will not be able to create a new document with it. If you will use another editor, it may not bother you. I a working with the following version:\nPython 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) \n"
] |
[
2,
0
] |
[] |
[] |
[
"macos",
"osx_snow_leopard",
"python"
] |
stackoverflow_0002196823_macos_osx_snow_leopard_python.txt
|
Q:
Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass?
Every object I know of in Python can take care of its base class initialization by calling:
super(BaseClass, self).__init__()
This doesn't seem to be the case with a subclass of threading.Thread, since if I try this in SubClass.__init__(), I get:
RuntimeError: thread.__init__() not called
What gives this error? I looked at the source for threading.Thread and it looks like that __init__ method should set Thread.__initialized = True. I see that all examples use the following __init__:
class YourThread(threading.Thread):
def __init__(self, *args):
threading.Thread.__init__(self)
# whatev else
But why?
A:
This works fine:
>>> class MyThread(threading.Thread):
... def __init__(self):
... super(MyThread, self).__init__()
I think your code's bug is that you're passing the base class, rather than the current class, to super -- i.e. you're calling super(threading.Thread, ..., and that's just wrong. Hard to say since you don't show your failing code, but that's what I infer obliquely from the language you're using!-)
|
Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass?
|
Every object I know of in Python can take care of its base class initialization by calling:
super(BaseClass, self).__init__()
This doesn't seem to be the case with a subclass of threading.Thread, since if I try this in SubClass.__init__(), I get:
RuntimeError: thread.__init__() not called
What gives this error? I looked at the source for threading.Thread and it looks like that __init__ method should set Thread.__initialized = True. I see that all examples use the following __init__:
class YourThread(threading.Thread):
def __init__(self, *args):
threading.Thread.__init__(self)
# whatev else
But why?
|
[
"This works fine:\n>>> class MyThread(threading.Thread):\n... def __init__(self):\n... super(MyThread, self).__init__()\n\nI think your code's bug is that you're passing the base class, rather than the current class, to super -- i.e. you're calling super(threading.Thread, ..., and that's just wrong. Hard to say since you don't show your failing code, but that's what I infer obliquely from the language you're using!-)\n"
] |
[
43
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0002197563_multithreading_python.txt
|
Q:
Complex SQL optimization vs. general-purpose language
How might I optimize this query? The schema:
mysql> show columns from transactionlog;
+---------------+-------------------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------------------------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| transactionid | varchar(10) | NO | MUL | NULL | |
| queryid | tinyint(4) | NO | | NULL | |
| tableid | varchar(30) | NO | MUL | NULL | |
| tupleid | int(11) | NO | | NULL | |
| querytype | enum('select','insert','delete','update') | NO | | NULL | |
| schemaname | varchar(20) | YES | | NULL | |
| partition | tinyint(3) unsigned | YES | | NULL | |
+---------------+-------------------------------------------+------+-----+---------+----------------+
8 rows in set (0.04 sec)
The query:
select concat(weight, ' ', ids, '\n')
from (
select
tableid,
tupleid,
group_concat(id separator ' ') as ids,
(
select count(distinct transactionid)
from transactionlog
where transactionid in (
select transactionid
from transactionlog
where (tableid, tupleid, querytype) =
(t.tableid, t.tupleid, 'update')
group by transactionid
having count(*) > 0
)
) weight
from transactionlog t
group by tableid, tupleid
having weight > 0 and count(*) > 1
) u;
This is the output of EXPLAIN and mk-visual-explain:
+----+--------------------+----------------+-------+---------------+---------------+---------+-----------+------+------------------------------
----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+----------------+-------+---------------+---------------+---------+-----------+------+----------------------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 13 | |
| 2 | DERIVED | t | ALL | NULL | NULL | NULL | NULL | 68 | Using filesort |
| 3 | DEPENDENT SUBQUERY | transactionlog | index | NULL | transactionid | 12 | NULL | 68 | Using where; Using index |
| 4 | DEPENDENT SUBQUERY | transactionlog | ref | tableid | tableid | 36 | func,func | 2 | Using where; Using temporary; Using filesort |
+----+--------------------+----------------+-------+---------------+---------------+---------+-----------+------+----------------------------------------------+
Table scan
rows 13
+- DERIVED
table derived(t,transactionlog,temporary(transactionlog))
+- DEPENDENT SUBQUERY
+- DEPENDENT SUBQUERY
| +- Filesort
| | +- TEMPORARY
| | table temporary(transactionlog)
| | +- Filter with WHERE
| | +- Bookmark lookup
| | +- Table
| | | table transactionlog
| | | possible_keys tableid
| | +- Index lookup
| | key transactionlog->tableid
| | possible_keys tableid
| | key_len 36
| | ref func,func
| | rows 2
| +- Filter with WHERE
| +- Index scan
| key transactionlog->transactionid
| key_len 12
| rows 68
+- Filesort
+- Table scan
rows 68
+- Table
table t
That is a lot of work. I can write the equivalent logic in Python while making a single pass:
results = query("""
select tableid, tupleid, transactionid, id, querytype
from transactionlog_2warehouse
""")
_tab, _tup = None
ids = []
weight = 0
saw_upd = False
for tab, tup, txn, id, qt in results:
if (_tab, _tup) != (tab, tup):
if len(ids) > 1 and weight > 0:
print weight, ids
weight = 0
ids = []
_txn = None
if _txn != txn:
saw_upd = False
if qt == 'update' and not saw_upd:
weight += 1
saw_upd = True
ids += [id]
Is it possible to achieve the Python single-pass performance using pure SQL? Thanks in advance!
A:
Use:
SELECT CONCAT(x.weight, ' ', GROUP_CONCAT(t.id SEPARATOR ' '), '\n')
FROM TRANSACTIONLOG t
JOIN (SELECT tl.tableid,
tl.tupleid,
COUNT(DISTINCT tl.transactionid) AS weight
FROM TRANSACTIONLOG tl
WHERE tl.querytype = 'update'
GROUP BY tl.tableid, tl.tupleid) x ON x.tableid = t.tableid
AND x.tupleid = t.tupleid
AND x.weight > 0
GROUP BY t.tableid, t.tupleid, x.weight
HAVING COUNT(*) > 1
|
Complex SQL optimization vs. general-purpose language
|
How might I optimize this query? The schema:
mysql> show columns from transactionlog;
+---------------+-------------------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------------------------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| transactionid | varchar(10) | NO | MUL | NULL | |
| queryid | tinyint(4) | NO | | NULL | |
| tableid | varchar(30) | NO | MUL | NULL | |
| tupleid | int(11) | NO | | NULL | |
| querytype | enum('select','insert','delete','update') | NO | | NULL | |
| schemaname | varchar(20) | YES | | NULL | |
| partition | tinyint(3) unsigned | YES | | NULL | |
+---------------+-------------------------------------------+------+-----+---------+----------------+
8 rows in set (0.04 sec)
The query:
select concat(weight, ' ', ids, '\n')
from (
select
tableid,
tupleid,
group_concat(id separator ' ') as ids,
(
select count(distinct transactionid)
from transactionlog
where transactionid in (
select transactionid
from transactionlog
where (tableid, tupleid, querytype) =
(t.tableid, t.tupleid, 'update')
group by transactionid
having count(*) > 0
)
) weight
from transactionlog t
group by tableid, tupleid
having weight > 0 and count(*) > 1
) u;
This is the output of EXPLAIN and mk-visual-explain:
+----+--------------------+----------------+-------+---------------+---------------+---------+-----------+------+------------------------------
----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+----------------+-------+---------------+---------------+---------+-----------+------+----------------------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 13 | |
| 2 | DERIVED | t | ALL | NULL | NULL | NULL | NULL | 68 | Using filesort |
| 3 | DEPENDENT SUBQUERY | transactionlog | index | NULL | transactionid | 12 | NULL | 68 | Using where; Using index |
| 4 | DEPENDENT SUBQUERY | transactionlog | ref | tableid | tableid | 36 | func,func | 2 | Using where; Using temporary; Using filesort |
+----+--------------------+----------------+-------+---------------+---------------+---------+-----------+------+----------------------------------------------+
Table scan
rows 13
+- DERIVED
table derived(t,transactionlog,temporary(transactionlog))
+- DEPENDENT SUBQUERY
+- DEPENDENT SUBQUERY
| +- Filesort
| | +- TEMPORARY
| | table temporary(transactionlog)
| | +- Filter with WHERE
| | +- Bookmark lookup
| | +- Table
| | | table transactionlog
| | | possible_keys tableid
| | +- Index lookup
| | key transactionlog->tableid
| | possible_keys tableid
| | key_len 36
| | ref func,func
| | rows 2
| +- Filter with WHERE
| +- Index scan
| key transactionlog->transactionid
| key_len 12
| rows 68
+- Filesort
+- Table scan
rows 68
+- Table
table t
That is a lot of work. I can write the equivalent logic in Python while making a single pass:
results = query("""
select tableid, tupleid, transactionid, id, querytype
from transactionlog_2warehouse
""")
_tab, _tup = None
ids = []
weight = 0
saw_upd = False
for tab, tup, txn, id, qt in results:
if (_tab, _tup) != (tab, tup):
if len(ids) > 1 and weight > 0:
print weight, ids
weight = 0
ids = []
_txn = None
if _txn != txn:
saw_upd = False
if qt == 'update' and not saw_upd:
weight += 1
saw_upd = True
ids += [id]
Is it possible to achieve the Python single-pass performance using pure SQL? Thanks in advance!
|
[
"Use:\n SELECT CONCAT(x.weight, ' ', GROUP_CONCAT(t.id SEPARATOR ' '), '\\n')\n FROM TRANSACTIONLOG t\n JOIN (SELECT tl.tableid,\n tl.tupleid,\n COUNT(DISTINCT tl.transactionid) AS weight\n FROM TRANSACTIONLOG tl\n WHERE tl.querytype = 'update'\n GROUP BY tl.tableid, tl.tupleid) x ON x.tableid = t.tableid\n AND x.tupleid = t.tupleid\n AND x.weight > 0\nGROUP BY t.tableid, t.tupleid, x.weight\n HAVING COUNT(*) > 1\n\n"
] |
[
0
] |
[] |
[] |
[
"mysql",
"optimization",
"python",
"sql"
] |
stackoverflow_0002197579_mysql_optimization_python_sql.txt
|
Q:
How to Handle EOFError for raw_input() in python in Mac OS X
My python program has two calls to raw_input()
The first raw_input() is to take multiline input from the user. The user can issue Ctrl+D (Ctrl+Z in windows) for the end of input.
Second raw_input() should take another input from user with (y/n) type prompt.
Unfortunately (in Mac OS X only?), second raw_input() raises EOFError when the stdin is terminated (with Ctrl+D) at first raw_input() prompt.
Please see my example code below for more explanation -
mailBody = ''
signature = 'Later!'
print 'Compose your mail:'
while True:
try:
# Hit ^D after entering some text
mailBody+= raw_input()
mailBody+='\n'
except EOFError:
break
# This raw_input() throws EOFError too. Because, stdin is terminated for the session
# when EOF (^D) is issues at first raw_input() method (Where as, it doesn't raise EOFError in Linux)
opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower()
print '-'*10+'Your Mail'
if opt == 'y':
print mailBody+"\n"+signature
else:
print mailBody
print '-'*19
The program output:
-1- abhinay@MacBook code/py % python prompt.py
Compose your mail:
hello there!
how is everybody?
Do you want to add signature to your mail? (y/N): Traceback (most recent call last):
File "prompt.py", line 11, in <module>
opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower()
EOFError
How can I make second prompt not to raise EOFError. Please help!
EDIT:
I've edited my question to keep it simple.
I ran my above code in Linux System, it works without any issue. That is, the user was prompted at second raw_input() to receive '(y/N)' choice.
A:
It's quite normal that when standard input is terminated (by hitting control-D, in Unix-derived systems -- I think it's control-Z in Windows), it stays terminated thereafter (unless you close and re-open it in the meantime, of course).
|
How to Handle EOFError for raw_input() in python in Mac OS X
|
My python program has two calls to raw_input()
The first raw_input() is to take multiline input from the user. The user can issue Ctrl+D (Ctrl+Z in windows) for the end of input.
Second raw_input() should take another input from user with (y/n) type prompt.
Unfortunately (in Mac OS X only?), second raw_input() raises EOFError when the stdin is terminated (with Ctrl+D) at first raw_input() prompt.
Please see my example code below for more explanation -
mailBody = ''
signature = 'Later!'
print 'Compose your mail:'
while True:
try:
# Hit ^D after entering some text
mailBody+= raw_input()
mailBody+='\n'
except EOFError:
break
# This raw_input() throws EOFError too. Because, stdin is terminated for the session
# when EOF (^D) is issues at first raw_input() method (Where as, it doesn't raise EOFError in Linux)
opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower()
print '-'*10+'Your Mail'
if opt == 'y':
print mailBody+"\n"+signature
else:
print mailBody
print '-'*19
The program output:
-1- abhinay@MacBook code/py % python prompt.py
Compose your mail:
hello there!
how is everybody?
Do you want to add signature to your mail? (y/N): Traceback (most recent call last):
File "prompt.py", line 11, in <module>
opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower()
EOFError
How can I make second prompt not to raise EOFError. Please help!
EDIT:
I've edited my question to keep it simple.
I ran my above code in Linux System, it works without any issue. That is, the user was prompted at second raw_input() to receive '(y/N)' choice.
|
[
"It's quite normal that when standard input is terminated (by hitting control-D, in Unix-derived systems -- I think it's control-Z in Windows), it stays terminated thereafter (unless you close and re-open it in the meantime, of course).\n"
] |
[
6
] |
[] |
[] |
[
"eof",
"eoferror",
"macos",
"python"
] |
stackoverflow_0002197891_eof_eoferror_macos_python.txt
|
Q:
Convert "little endian" hex string to IP address in Python
What's the best way to turn a string in this form into an IP address: "0200A8C0". The "octets" present in the string are in reverse order, i.e. the given example string should generate 192.168.0.2.
A:
Network address manipulation is provided by the socket module.
socket.inet_ntoa(packed_ip)
Convert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument.
You can translate your hex string to packed ip using struct.pack()
and the little endian, unsigned long format.
s = "0200A8C0"
import socket
import struct
addr_long = int(s, 16)
print(hex(addr_long)) # '0x200a8c0'
print(struct.pack("<L", addr_long)) # '\xc0\xa8\x00\x02'
print(socket.inet_ntoa(struct.pack("<L", addr_long))) # '192.168.0.2'
A:
>>> s = "0200A8C0"
>>> bytes = ["".join(x) for x in zip(*[iter(s)]*2)]
>>> bytes
['02', '00', 'A8', 'C0']
>>> bytes = [int(x, 16) for x in bytes]
>>> bytes
[2, 0, 168, 192]
>>> print ".".join(str(x) for x in reversed(bytes))
192.168.0.2
It is short and clear; wrap it up in a function with error checking to suit your needs.
Handy grouping functions:
def group(iterable, n=2, missing=None, longest=True):
"""Group from a single iterable into groups of n.
Derived from http://bugs.python.org/issue1643
"""
if n < 1:
raise ValueError("invalid n")
args = (iter(iterable),) * n
if longest:
return itertools.izip_longest(*args, fillvalue=missing)
else:
return itertools.izip(*args)
def group_some(iterable, n=2):
"""Group from a single iterable into groups of at most n."""
if n < 1:
raise ValueError("invalid n")
iterable = iter(iterable)
while True:
L = list(itertools.islice(iterable, n))
if L:
yield L
else:
break
A:
You could do something like this:
>>> s = '0200A8C0'
>>> octets = [s[i:i+2] for i in range(0, len(s), 2)]
>>> ip = [int(i, 16) for i in reversed(octets)]
>>> ip_formatted = '.'.join(str(i) for i in ip)
>>> print ip_formatted
192.168.0.2
The octet splitting could probably be done more elegantly, but I can't think of a simpler way off the top of my head.
EDIT: Or on one line:
>>> s = '0200A8C0'
>>> print '.'.join(str(int(i, 16)) for i in reversed([s[i:i+2] for i in range(0, len(s), 2)]))
192.168.0.2
A:
My try:
a = '0200A8C0'
indices = range(0, 8, 2)
data = [str(int(a[x:x+2], 16)) for x in indices]
'.'.join(reversed(data))
|
Convert "little endian" hex string to IP address in Python
|
What's the best way to turn a string in this form into an IP address: "0200A8C0". The "octets" present in the string are in reverse order, i.e. the given example string should generate 192.168.0.2.
|
[
"Network address manipulation is provided by the socket module.\n\nsocket.inet_ntoa(packed_ip)\nConvert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument.\n\nYou can translate your hex string to packed ip using struct.pack()\nand the little endian, unsigned long format.\ns = \"0200A8C0\"\n\nimport socket\nimport struct\naddr_long = int(s, 16)\nprint(hex(addr_long)) # '0x200a8c0'\nprint(struct.pack(\"<L\", addr_long)) # '\\xc0\\xa8\\x00\\x02'\nprint(socket.inet_ntoa(struct.pack(\"<L\", addr_long))) # '192.168.0.2'\n\n",
">>> s = \"0200A8C0\"\n>>> bytes = [\"\".join(x) for x in zip(*[iter(s)]*2)]\n>>> bytes\n['02', '00', 'A8', 'C0']\n>>> bytes = [int(x, 16) for x in bytes]\n>>> bytes\n[2, 0, 168, 192]\n>>> print \".\".join(str(x) for x in reversed(bytes))\n192.168.0.2\n\nIt is short and clear; wrap it up in a function with error checking to suit your needs.\n\nHandy grouping functions:\ndef group(iterable, n=2, missing=None, longest=True):\n \"\"\"Group from a single iterable into groups of n.\n\n Derived from http://bugs.python.org/issue1643\n \"\"\"\n if n < 1:\n raise ValueError(\"invalid n\")\n args = (iter(iterable),) * n\n if longest:\n return itertools.izip_longest(*args, fillvalue=missing)\n else:\n return itertools.izip(*args)\n\ndef group_some(iterable, n=2):\n \"\"\"Group from a single iterable into groups of at most n.\"\"\"\n if n < 1:\n raise ValueError(\"invalid n\")\n iterable = iter(iterable)\n while True:\n L = list(itertools.islice(iterable, n))\n if L:\n yield L\n else:\n break\n\n",
"You could do something like this:\n>>> s = '0200A8C0'\n>>> octets = [s[i:i+2] for i in range(0, len(s), 2)]\n>>> ip = [int(i, 16) for i in reversed(octets)]\n>>> ip_formatted = '.'.join(str(i) for i in ip)\n>>> print ip_formatted\n192.168.0.2\n\nThe octet splitting could probably be done more elegantly, but I can't think of a simpler way off the top of my head.\nEDIT: Or on one line:\n>>> s = '0200A8C0'\n>>> print '.'.join(str(int(i, 16)) for i in reversed([s[i:i+2] for i in range(0, len(s), 2)]))\n192.168.0.2\n\n",
"My try:\na = '0200A8C0'\nindices = range(0, 8, 2)\ndata = [str(int(a[x:x+2], 16)) for x in indices]\n'.'.join(reversed(data))\n\n"
] |
[
35,
7,
3,
0
] |
[] |
[] |
[
"endianness",
"ip_address",
"python",
"sockets"
] |
stackoverflow_0002197974_endianness_ip_address_python_sockets.txt
|
Q:
python file reading
I have file /tmp/gs.pid with content
client01: 25778
I would like retrieve the second word from it.
ie. 25778.
I have tried below code but it didn't work.
>>> f=open ("/tmp/gs.pid","r")
>>> for line in f:
... word=line.strip().lower()
... print "\n -->" , word
A:
Try this:
>>> f = open("/tmp/gs.pid", "r")
>>> for line in f:
... word = line.strip().split()[1].lower()
... print " -->", word
>>> f.close()
It will print the second word of every line in lowercase. split() will take your line and split it on any whitespace and return a list, then indexing with [1] will take the second element of the list and lower() will convert the result to lowercase. Note that it would make sense to check whether there are at least 2 words on the line, for example:
>>> f = open("/tmp/gs.pid", "r")
>>> for line in f:
... words = line.strip().split()
... if len(words) >= 2:
... print " -->", words[1].lower()
... else:
... print 'Line contains fewer than 2 words.'
>>> f.close()
A:
word="client01: 25778"
pid=word.split(": ")[1] #or word.split()[1] to split from the separator
A:
If all lines are of the form abc: def, you can extract the 2nd part with
second_part = line[line.find(": ")+2:]
If not you need to verify line.find(": ") really returns a nonnegative number first.
with open("/tmp/gs.pid") as f:
for line in f:
p = line.find(": ")
if p != -1:
second_part = line[p+2:].lower()
print "\n -->", second_part
A:
>>> open("/tmp/gs.pid").read().split()[1]
'25778'
|
python file reading
|
I have file /tmp/gs.pid with content
client01: 25778
I would like retrieve the second word from it.
ie. 25778.
I have tried below code but it didn't work.
>>> f=open ("/tmp/gs.pid","r")
>>> for line in f:
... word=line.strip().lower()
... print "\n -->" , word
|
[
"Try this:\n>>> f = open(\"/tmp/gs.pid\", \"r\")\n>>> for line in f:\n ... word = line.strip().split()[1].lower()\n ... print \" -->\", word\n>>> f.close()\n\nIt will print the second word of every line in lowercase. split() will take your line and split it on any whitespace and return a list, then indexing with [1] will take the second element of the list and lower() will convert the result to lowercase. Note that it would make sense to check whether there are at least 2 words on the line, for example:\n>>> f = open(\"/tmp/gs.pid\", \"r\")\n>>> for line in f:\n ... words = line.strip().split()\n ... if len(words) >= 2:\n ... print \" -->\", words[1].lower()\n ... else:\n ... print 'Line contains fewer than 2 words.'\n>>> f.close()\n\n",
"word=\"client01: 25778\"\npid=word.split(\": \")[1] #or word.split()[1] to split from the separator\n\n",
"If all lines are of the form abc: def, you can extract the 2nd part with\nsecond_part = line[line.find(\": \")+2:]\n\nIf not you need to verify line.find(\": \") really returns a nonnegative number first.\nwith open(\"/tmp/gs.pid\") as f:\n for line in f:\n p = line.find(\": \")\n if p != -1:\n second_part = line[p+2:].lower()\n print \"\\n -->\", second_part\n\n",
">>> open(\"/tmp/gs.pid\").read().split()[1]\n'25778'\n\n"
] |
[
7,
1,
1,
1
] |
[] |
[] |
[
"file",
"python",
"string"
] |
stackoverflow_0002197958_file_python_string.txt
|
Q:
Python's layout of low-value ints in memory
My question is: where do these patterns (below) originate?
I learned (somewhere) that Python has unique "copies", if that's the right word, for small integers. For example:
>>> x = y = 0
>>> id(0)
4297074752
>>> id(x)
4297074752
>>> id(y)
4297074752
>>> x += 1
>>> id(x)
4297074728
>>> y
0
When I look at the memory locations of ints, there is a simple pattern early:
>>> N = id(0)
>>> for i in range(5):
... print i, N - id(i)
...
0 0
1 24
2 48
3 72
4 96
>>> bin(24)
'0b11000'
It's not clear to me why this is chosen as the increment. Moreover, I can't explain this pattern at all above 256:
>>> prev = 0
>>> for i in range(270):
... t = (id(i-1), id(i))
... diff = t[0] - t[1]
... if diff != prev:
... print i-1, i, t, diff
... prev = diff
...
-1 0 (4297074776, 4297074752) 24
35 36 (4297073912, 4297075864) -1952
36 37 (4297075864, 4297075840) 24
76 77 (4297074904, 4297076856) -1952
77 78 (4297076856, 4297076832) 24
117 118 (4297075896, 4297077848) -1952
118 119 (4297077848, 4297077824) 24
158 159 (4297076888, 4297078840) -1952
159 160 (4297078840, 4297078816) 24
199 200 (4297077880, 4297079832) -1952
200 201 (4297079832, 4297079808) 24
240 241 (4297078872, 4297080824) -1952
241 242 (4297080824, 4297080800) 24
256 257 (4297080464, 4297155264) -74800
257 258 (4297155072, 4297155288) -216
259 260 (4297155072, 4297155336) -264
260 261 (4297155048, 4297155432) -384
261 262 (4297155024, 4297155456) -432
262 263 (4297380280, 4297155384) 224896
263 264 (4297155000, 4297155240) -240
264 265 (4297155072, 4297155216) -144
266 267 (4297155072, 4297155168) -96
267 268 (4297155024, 4297155144) -120
Any thoughts, clues, places to look?
Edit: and what's special about 24?
Update: The standard library has sys.getsizeof() which returns 24 when I call it with 1 as argument. That's a lot of bytes, but on a 64-bit machine, we have 8 bytes each for the type, the value and the ref count. Also, see here, and the C API reference here.
Spent some time with the "source" in the link from Peter Hansen in comments. Couldn't find the definition of an int (beyond a declaration of *int_int), but I did find:
#define NSMALLPOSINTS 257
#define NSMALLNEGINTS 5
A:
Low-value integers are preallocated, high value integers are allocated whenever they are computed. Integers that appear in source code are the same object. On my system,
>>> id(2) == id(1+1)
True
>>> id(1000) == id(1000+0)
False
>>> id(1000) == id(1000)
True
You'll also notice that the ids depend on the system. They're just memory addresses, assigned by the system allocator (or possibly the linker, for static objects?)
>>> id(0)
8402324
Edit: The reason id(1000) == id(1000) is because the Python compiler notices that two of the integer constants in the code it's compiling are the same, so it only allocates one object for both. This would be an unacceptable performance hit at runtime, but at compile time it's not noticeable. (Yes, the interpreter is also a compiler. Most interpreters are also compilers, very few aren't.)
A:
The first 256 ints are preallocated
>>> for n in range(1000):
>>> if id(n) != id(n+0):
>>> print n
>>> break
257
A:
I seem to recall that Python internally caches copies of ints < 256 to save having to create new Python objects for commonly-used cases. So once you go over 256 you're getting newly created objects each time which may appear to be 'randomly' laid out in memory (obviously their locations would make sense to Python's allocator, but probably not to us).
A:
Since others have fully answered why ids have a distinct pattern up to 256, I thought I would answer your addendum instead: 24 is the size in bytes of an integer object in python. When the first 256 integers are allocated they are done so contiguously in memory, leading to a difference of 24 between each memory address.
A:
integers up to 256 are interned, that's why you see a "pattern" there. All other integers are created during execution and as such allocated random id.
A:
In CPython, IDs are the address of the objects.
|
Python's layout of low-value ints in memory
|
My question is: where do these patterns (below) originate?
I learned (somewhere) that Python has unique "copies", if that's the right word, for small integers. For example:
>>> x = y = 0
>>> id(0)
4297074752
>>> id(x)
4297074752
>>> id(y)
4297074752
>>> x += 1
>>> id(x)
4297074728
>>> y
0
When I look at the memory locations of ints, there is a simple pattern early:
>>> N = id(0)
>>> for i in range(5):
... print i, N - id(i)
...
0 0
1 24
2 48
3 72
4 96
>>> bin(24)
'0b11000'
It's not clear to me why this is chosen as the increment. Moreover, I can't explain this pattern at all above 256:
>>> prev = 0
>>> for i in range(270):
... t = (id(i-1), id(i))
... diff = t[0] - t[1]
... if diff != prev:
... print i-1, i, t, diff
... prev = diff
...
-1 0 (4297074776, 4297074752) 24
35 36 (4297073912, 4297075864) -1952
36 37 (4297075864, 4297075840) 24
76 77 (4297074904, 4297076856) -1952
77 78 (4297076856, 4297076832) 24
117 118 (4297075896, 4297077848) -1952
118 119 (4297077848, 4297077824) 24
158 159 (4297076888, 4297078840) -1952
159 160 (4297078840, 4297078816) 24
199 200 (4297077880, 4297079832) -1952
200 201 (4297079832, 4297079808) 24
240 241 (4297078872, 4297080824) -1952
241 242 (4297080824, 4297080800) 24
256 257 (4297080464, 4297155264) -74800
257 258 (4297155072, 4297155288) -216
259 260 (4297155072, 4297155336) -264
260 261 (4297155048, 4297155432) -384
261 262 (4297155024, 4297155456) -432
262 263 (4297380280, 4297155384) 224896
263 264 (4297155000, 4297155240) -240
264 265 (4297155072, 4297155216) -144
266 267 (4297155072, 4297155168) -96
267 268 (4297155024, 4297155144) -120
Any thoughts, clues, places to look?
Edit: and what's special about 24?
Update: The standard library has sys.getsizeof() which returns 24 when I call it with 1 as argument. That's a lot of bytes, but on a 64-bit machine, we have 8 bytes each for the type, the value and the ref count. Also, see here, and the C API reference here.
Spent some time with the "source" in the link from Peter Hansen in comments. Couldn't find the definition of an int (beyond a declaration of *int_int), but I did find:
#define NSMALLPOSINTS 257
#define NSMALLNEGINTS 5
|
[
"Low-value integers are preallocated, high value integers are allocated whenever they are computed. Integers that appear in source code are the same object. On my system,\n>>> id(2) == id(1+1)\nTrue\n>>> id(1000) == id(1000+0)\nFalse\n>>> id(1000) == id(1000)\nTrue\n\nYou'll also notice that the ids depend on the system. They're just memory addresses, assigned by the system allocator (or possibly the linker, for static objects?)\n>>> id(0)\n8402324\n\nEdit: The reason id(1000) == id(1000) is because the Python compiler notices that two of the integer constants in the code it's compiling are the same, so it only allocates one object for both. This would be an unacceptable performance hit at runtime, but at compile time it's not noticeable. (Yes, the interpreter is also a compiler. Most interpreters are also compilers, very few aren't.)\n",
"The first 256 ints are preallocated\n>>> for n in range(1000):\n>>> if id(n) != id(n+0):\n>>> print n\n>>> break\n\n257\n\n",
"I seem to recall that Python internally caches copies of ints < 256 to save having to create new Python objects for commonly-used cases. So once you go over 256 you're getting newly created objects each time which may appear to be 'randomly' laid out in memory (obviously their locations would make sense to Python's allocator, but probably not to us).\n",
"Since others have fully answered why ids have a distinct pattern up to 256, I thought I would answer your addendum instead: 24 is the size in bytes of an integer object in python. When the first 256 integers are allocated they are done so contiguously in memory, leading to a difference of 24 between each memory address.\n",
"integers up to 256 are interned, that's why you see a \"pattern\" there. All other integers are created during execution and as such allocated random id.\n",
"In CPython, IDs are the address of the objects.\n"
] |
[
8,
2,
2,
2,
1,
0
] |
[] |
[] |
[
"memory",
"python"
] |
stackoverflow_0002195964_memory_python.txt
|
Q:
Importing globally and locally
I created a module which is going to be used in several python scripts. The structure is as follows:
Main file:
import numpy as np
from mymodule import newfunction
f = np.arange(100,200,1)
a = np.zeros(np.shape(f))
c = newfunction(f)
mymodule.py:
def newfunction(f):
import numpy as np
b = np.zeros(np.shape(f))
return b
if __name__ == "__main__":
import numpy as np
Don't mind the functionality of this program, but the problem is that when I run it, I get "NameError: global name 'zeros' is not defined".
What am I missing out on here?
A:
mymodule.py doesn't see:
import numpy as np
statement(s). "import" statement in Python doesn't work like #include in C++, it merely creates new dictionary of objects contained in imported module. If you want to use 'np' identifier within that dictionary, you have to explicitly import it there.
Regarding
if __name__ == "__main__":
import numpy as np
-- this is only called when you execute mymodule.py as standalone script, which probably is not the case in this question.
EDIT:
OP changed sample code, by adding import numpy as np inside his function, and my answer is for the original question.
|
Importing globally and locally
|
I created a module which is going to be used in several python scripts. The structure is as follows:
Main file:
import numpy as np
from mymodule import newfunction
f = np.arange(100,200,1)
a = np.zeros(np.shape(f))
c = newfunction(f)
mymodule.py:
def newfunction(f):
import numpy as np
b = np.zeros(np.shape(f))
return b
if __name__ == "__main__":
import numpy as np
Don't mind the functionality of this program, but the problem is that when I run it, I get "NameError: global name 'zeros' is not defined".
What am I missing out on here?
|
[
"mymodule.py doesn't see:\n import numpy as np\n\nstatement(s). \"import\" statement in Python doesn't work like #include in C++, it merely creates new dictionary of objects contained in imported module. If you want to use 'np' identifier within that dictionary, you have to explicitly import it there.\nRegarding\n if __name__ == \"__main__\":\n import numpy as np\n\n-- this is only called when you execute mymodule.py as standalone script, which probably is not the case in this question.\nEDIT: \nOP changed sample code, by adding import numpy as np inside his function, and my answer is for the original question. \n"
] |
[
3
] |
[] |
[] |
[
"import",
"module",
"python"
] |
stackoverflow_0002198082_import_module_python.txt
|
Q:
How do I update my version of Django?
I currently have it installed and it's running a website.
http://www.djangoproject.com/download/
This is the new version. How do I upgrade it? (How do I install the new version over my current one?)
A:
read about this in :
http://docs.djangoproject.com/en/dev/topics/install/
For installing Django to be able to update to the latest code in trunk:
If you'd like to be able to update
your Django code occasionally with the
latest bug fixes and improvements,
follow these instructions:
1.Make sure that you have Subversion installed, and that you can run its
commands from a shell. (Enter svn help
at a shell prompt to test this.)
2.Check out Django's main development branch (the 'trunk') like so:
svn co
http://code.djangoproject.com/svn/django/trunk/
django-trunk
3.Next, make sure that the Python interpreter can load Django's code.
There are various ways of
accomplishing this. One of the most
convenient, on Linux, Mac OSX or other
Unix-like systems, is to use a
symbolic link:
ln -s pwd/django-trunk/django
SITE-PACKAGES-DIR/django (In the above
line, change SITE-PACKAGES-DIR to
match the location of your system's
site-packages directory, as explained
in the "Where are my site-packages
stored?" section above.)
Alternatively, you can define your
PYTHONPATH environment variable so
that it includes the django-trunk
directory. This is perhaps the most
convenient solution on Windows
systems, which don't support symbolic
links. (Environment variables can be
defined on Windows systems from the
Control Panel.)
What about Apache and mod_python?
If you take the approach of setting
PYTHONPATH, you'll need to remember to
do the same thing in your Apache
configuration once you deploy your
production site. Do this by setting
PythonPath in your Apache
configuration file.
More information about deployment is
available, of course, in our How to
use Django with mod_python
documentation.
4.On Unix-like systems, create a symbolic link to the file
django-trunk/django/bin/django-admin.py
in a directory on your system path,
such as /usr/local/bin. For example:
ln -s
pwd/django-trunk/django/bin/django-admin.py
/usr/local/bin This simply lets you
type django-admin.py from within any
directory, rather than having to
qualify the command with the full path
to the file.
On Windows systems, the same result
can be achieved by copying the file
django-trunk/django/bin/django-admin.py
to somewhere on your system path, for
example C:\Python24\Scripts.
You don't have to run python setup.py
install, because you've already
carried out the equivalent actions in
steps 3 and 4.
When you want to update your copy of
the Django source code, just run the
command svn update from within the
django-trunk directory. When you do
this, Subversion will automatically
download any changes
For updating Django from stable release to another stable release:
If you are upgrading your installation of Django from a previous
version, you will need to uninstall the old Django version before
installing the new version.
If you installed Django using setup.py install, uninstalling is as
simple as deleting the django directory from your Python
site-packages.
If you installed Django from a Python egg, remove the Django .egg
file, and remove the reference to the egg in the file named
easy-install.pth. This file should also be located in your
site-packages directory.
A:
First of all, don't. Install/upgrade it on your staging server first and test your app to make sure that it still works. Only after complete testing should you cut over to the new version on your production website.
|
How do I update my version of Django?
|
I currently have it installed and it's running a website.
http://www.djangoproject.com/download/
This is the new version. How do I upgrade it? (How do I install the new version over my current one?)
|
[
"read about this in :\nhttp://docs.djangoproject.com/en/dev/topics/install/\nFor installing Django to be able to update to the latest code in trunk:\n\nIf you'd like to be able to update\n your Django code occasionally with the\n latest bug fixes and improvements,\n follow these instructions:\n1.Make sure that you have Subversion installed, and that you can run its\n commands from a shell. (Enter svn help\n at a shell prompt to test this.)\n2.Check out Django's main development branch (the 'trunk') like so:\nsvn co\n http://code.djangoproject.com/svn/django/trunk/\n django-trunk\n 3.Next, make sure that the Python interpreter can load Django's code.\n There are various ways of\n accomplishing this. One of the most\n convenient, on Linux, Mac OSX or other\n Unix-like systems, is to use a\n symbolic link:\nln -s pwd/django-trunk/django\n SITE-PACKAGES-DIR/django (In the above\n line, change SITE-PACKAGES-DIR to\n match the location of your system's\n site-packages directory, as explained\n in the \"Where are my site-packages\n stored?\" section above.)\nAlternatively, you can define your\n PYTHONPATH environment variable so\n that it includes the django-trunk\n directory. This is perhaps the most\n convenient solution on Windows\n systems, which don't support symbolic\n links. (Environment variables can be\n defined on Windows systems from the\n Control Panel.)\nWhat about Apache and mod_python?\nIf you take the approach of setting\n PYTHONPATH, you'll need to remember to\n do the same thing in your Apache\n configuration once you deploy your\n production site. Do this by setting\n PythonPath in your Apache\n configuration file.\nMore information about deployment is\n available, of course, in our How to\n use Django with mod_python\n documentation.\n4.On Unix-like systems, create a symbolic link to the file\n django-trunk/django/bin/django-admin.py\n in a directory on your system path,\n such as /usr/local/bin. For example:\nln -s\n pwd/django-trunk/django/bin/django-admin.py\n /usr/local/bin This simply lets you\n type django-admin.py from within any\n directory, rather than having to\n qualify the command with the full path\n to the file.\nOn Windows systems, the same result\n can be achieved by copying the file\n django-trunk/django/bin/django-admin.py\n to somewhere on your system path, for\n example C:\\Python24\\Scripts.\nYou don't have to run python setup.py\n install, because you've already\n carried out the equivalent actions in\n steps 3 and 4.\nWhen you want to update your copy of\n the Django source code, just run the\n command svn update from within the\n django-trunk directory. When you do\n this, Subversion will automatically\n download any changes\n\nFor updating Django from stable release to another stable release:\n\nIf you are upgrading your installation of Django from a previous\n version, you will need to uninstall the old Django version before\n installing the new version.\nIf you installed Django using setup.py install, uninstalling is as\n simple as deleting the django directory from your Python\n site-packages.\nIf you installed Django from a Python egg, remove the Django .egg\n file, and remove the reference to the egg in the file named\n easy-install.pth. This file should also be located in your\n site-packages directory.\n\n",
"First of all, don't. Install/upgrade it on your staging server first and test your app to make sure that it still works. Only after complete testing should you cut over to the new version on your production website.\n"
] |
[
5,
5
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002197919_django_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.