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:
Converting specific time format with strptime
I'm trying to convert
[16/Jan/2010:18:11:06 +0100] (common log format)
to a timestamp. How can I use strptime to convert this?
time zone can be different from +0100
A:
import time
log = '16/Jan/2010:18:11:06 +0100'
dt = time.strptime(log, '%d/%b/%Y:%H:%M:%S +0100')
Reference: http://docs.python.org/library/time.html#time.strptime
Python's timezone support is problematic and platform dependant.
See this post (see also its first part).
| Converting specific time format with strptime | I'm trying to convert
[16/Jan/2010:18:11:06 +0100] (common log format)
to a timestamp. How can I use strptime to convert this?
time zone can be different from +0100
| [
"import time\nlog = '16/Jan/2010:18:11:06 +0100'\ndt = time.strptime(log, '%d/%b/%Y:%H:%M:%S +0100')\n\nReference: http://docs.python.org/library/time.html#time.strptime\nPython's timezone support is problematic and platform dependant.\nSee this post (see also its first part). \n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003452188_python.txt |
Q:
How to detect HTTP Request in python + twisted?
I am learning network programming using twisted 10 in python. In below code is there any way to detect HTTP Request when data recieved? also retrieve Domain name, Sub Domain, Port values from this? Discard it if its not http data?
from twisted.internet import stdio, reactor, protocol
from twisted.protocols import basic
import re
class DataForwardingProtocol(protocol.Protocol):
def _ _init_ _(self):
self.output = None
self.normalizeNewlines = False
def dataReceived(self, data):
if self.normalizeNewlines:
data = re.sub(r"(\r\n|\n)", "\r\n", data)
if self.output:
self.output.write(data)
class StdioProxyProtocol(DataForwardingProtocol):
def connectionMade(self):
inputForwarder = DataForwardingProtocol( )
inputForwarder.output = self.transport
inputForwarder.normalizeNewlines = True
stdioWrapper = stdio.StandardIO(inputForwarder)
self.output = stdioWrapper
print "Connected to server. Press ctrl-C to close connection."
class StdioProxyFactory(protocol.ClientFactory):
protocol = StdioProxyProtocol
def clientConnectionLost(self, transport, reason):
reactor.stop( )
def clientConnectionFailed(self, transport, reason):
print reason.getErrorMessage( )
reactor.stop( )
if __name__ == '_ _main_ _':
import sys
if not len(sys.argv) == 3:
print "Usage: %s host port" % _ _file_ _
sys.exit(1)
reactor.connectTCP(sys.argv[1], int(sys.argv[2]), StdioProxyFactory( ))
reactor.run( )
A:
protocol.dataReceived, which you're overriding, is too low-level to serve for the purpose without smart buffering that you're not doing -- per the docs I just quoted,
Called whenever data is received.
Use this method to translate to a
higher-level message. Usually, some
callback will be made upon the receipt
of each complete protocol message.
Parameters
data
a string of
indeterminate length. Please keep in
mind that you will probably need to
buffer some data, as partial (or
multiple) protocol messages may be
received! I recommend that unit tests
for protocols call through to this
method with differing chunk sizes,
down to one byte at a time.
You appear to be completely ignoring this crucial part of the docs.
You could instead use LineReceiver.lineReceived (inheriting from protocols.basic.LineReceiver, of course) to take advantage of the fact that HTTP requests come in "lines" -- you'll still need to join up headers that are being sent as multiple lines, since as this tutorial says:
Header lines beginning with space or
tab are actually part of the previous
header line, folded into multiple
lines for easy reading.
Once you have a nicely formatted/parsed response (consider studying twisted.web's sources so see one way it could be done),
retrieve Domain name, Sub Domain, Port
values from this?
now the Host header (cfr the RFC section 14.23) is the one containing this info.
A:
Just based on what you seems to be attempting, I think the following would be the path of least resistance:
http://twistedmatrix.com/documents/10.0.0/api/twisted.web.proxy.html
That's the twisted class for building an HTTP Proxy. It will let you intercept the requests, look at the destination and look at the sender. You can also look at all the headers and the content going back and forth. You seem to be trying to re-write the HTTP Protocol and Proxy class that twisted has already provided for you. I hope this helps.
| How to detect HTTP Request in python + twisted? | I am learning network programming using twisted 10 in python. In below code is there any way to detect HTTP Request when data recieved? also retrieve Domain name, Sub Domain, Port values from this? Discard it if its not http data?
from twisted.internet import stdio, reactor, protocol
from twisted.protocols import basic
import re
class DataForwardingProtocol(protocol.Protocol):
def _ _init_ _(self):
self.output = None
self.normalizeNewlines = False
def dataReceived(self, data):
if self.normalizeNewlines:
data = re.sub(r"(\r\n|\n)", "\r\n", data)
if self.output:
self.output.write(data)
class StdioProxyProtocol(DataForwardingProtocol):
def connectionMade(self):
inputForwarder = DataForwardingProtocol( )
inputForwarder.output = self.transport
inputForwarder.normalizeNewlines = True
stdioWrapper = stdio.StandardIO(inputForwarder)
self.output = stdioWrapper
print "Connected to server. Press ctrl-C to close connection."
class StdioProxyFactory(protocol.ClientFactory):
protocol = StdioProxyProtocol
def clientConnectionLost(self, transport, reason):
reactor.stop( )
def clientConnectionFailed(self, transport, reason):
print reason.getErrorMessage( )
reactor.stop( )
if __name__ == '_ _main_ _':
import sys
if not len(sys.argv) == 3:
print "Usage: %s host port" % _ _file_ _
sys.exit(1)
reactor.connectTCP(sys.argv[1], int(sys.argv[2]), StdioProxyFactory( ))
reactor.run( )
| [
"protocol.dataReceived, which you're overriding, is too low-level to serve for the purpose without smart buffering that you're not doing -- per the docs I just quoted,\n\nCalled whenever data is received.\nUse this method to translate to a\n higher-level message. Usually, some\n callback will be made upon the rec... | [
3,
1
] | [] | [] | [
"http",
"packet",
"python",
"twisted"
] | stackoverflow_0003430689_http_packet_python_twisted.txt |
Q:
Running CGI outside of cgi-bin. Good idea?
I'm considering moving from PHP to Python (for personal projects), and I really don't like seeing /cgi-bin/ in my URL.
I got the Python to execute outside of cgi-bin, but I just wanted to make sure there were no possible security issues that could pop up, and that there were no major impacts on the speed.
So are there any major issues I need to be aware of?
Thanks in advance for any help.
A:
Being as how it's nominally just a URL, there aren't any impacts on speed per-se. However, it is standard practice, just like it's standard practice to make the entry page to a website index.html, but it's not required by any stretch (as evidenced by default.aspx, home.php, etc)
I would change it as a security through obscurity reference myself, were I inclined to change those things on my system.
While you won't incur any Apache security issues, there may be issues with server-side code or hard-coded modules that don't query for path, and assume code is running from cgi-bin ... just something to consider.
| Running CGI outside of cgi-bin. Good idea? | I'm considering moving from PHP to Python (for personal projects), and I really don't like seeing /cgi-bin/ in my URL.
I got the Python to execute outside of cgi-bin, but I just wanted to make sure there were no possible security issues that could pop up, and that there were no major impacts on the speed.
So are there any major issues I need to be aware of?
Thanks in advance for any help.
| [
"Being as how it's nominally just a URL, there aren't any impacts on speed per-se. However, it is standard practice, just like it's standard practice to make the entry page to a website index.html, but it's not required by any stretch (as evidenced by default.aspx, home.php, etc)\nI would change it as a security th... | [
1
] | [] | [] | [
"cgi",
"cgi_bin",
"python"
] | stackoverflow_0003452388_cgi_cgi_bin_python.txt |
Q:
twisted: Failure vs. Error
When should I use a twisted.python.failure.Failure, and when should I use something like twisted.internet.error.ConnectionDone? Or should I do twisted.python.failure.Failure(twisted.internet.error.ConnectionDone), and if so, in what casese should I do that?
A:
A Failure represents an exception and a traceback (often different from the current stack trace). You should use Failure when you are constructing an asynchronous exception. So, when you're going to fire a Deferred with an error, or when you're going to call a method like IProtocol.connectionLost or ClientFactory.clientConnectionFailed. This is because in such cases, you want the ability to associate a different stack trace with the exception than the current stack trace.
You shouldn't use Failure(ConnectionDone) because the correct one-argument invocation of Failure accepts an exception instance, not an exception class. So, instead, use Failure(ConnectionDone()). You can also use the zero-argument form to create a new Failure: Failure(). This only works when there is a "current" exception, eg in the suite of an except statement. It constructs the Failure using that current exception, as well as its traceback.
You can also construct a Failure with three-arguments, an exception class, instance, and traceback. This is most commonly done using the return value of sys.exc_info().
When you just want to raise an exception, you don't need to create a Failure. Just do what you'd normally do in a Python program to raise an exception: raise SomeException(...).
| twisted: Failure vs. Error | When should I use a twisted.python.failure.Failure, and when should I use something like twisted.internet.error.ConnectionDone? Or should I do twisted.python.failure.Failure(twisted.internet.error.ConnectionDone), and if so, in what casese should I do that?
| [
"A Failure represents an exception and a traceback (often different from the current stack trace). You should use Failure when you are constructing an asynchronous exception. So, when you're going to fire a Deferred with an error, or when you're going to call a method like IProtocol.connectionLost or ClientFactor... | [
10
] | [] | [] | [
"exception",
"exception_handling",
"python",
"twisted"
] | stackoverflow_0003452022_exception_exception_handling_python_twisted.txt |
Q:
wxPython: How do I find out which widget has the focus?
How do I find out which widget in my wx.Frame has the focus?
A:
You should be able to use the Window class's static FindFocus() method to return the object that has focus.
api: http://www.wxpython.org/docs/api/wx.Window-class.html#FindFocus
examples: http://nullege.com/codes/search/wx.Window.FindFocus/all/page:2
| wxPython: How do I find out which widget has the focus? | How do I find out which widget in my wx.Frame has the focus?
| [
"You should be able to use the Window class's static FindFocus() method to return the object that has focus.\napi: http://www.wxpython.org/docs/api/wx.Window-class.html#FindFocus\nexamples: http://nullege.com/codes/search/wx.Window.FindFocus/all/page:2\n"
] | [
10
] | [] | [] | [
"focus",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0003452489_focus_python_wxpython_wxwidgets.txt |
Q:
Big picture questions regarding Django, Java, Python, HTML and web-site development in general
I am trying to get a handle on the state of the art regarding web site development and have several questions. Maybe I'll end up finding most of the answers on my own. I come from a background of C++ and Windows development, and generally I am befuddled by what seems to be the ad-hoc nature of web development.
I focussed in on Django, after online research of it and Ruby (on Rails). From what I read, ROR tries to do everything for you behind the scenes and so therefore is slow and unscalable (and overhyped and not ready for prime time). So I have gotten into Django - downloaded Python and Django, the source from a complete Django site, got it running, and so forth.
And the first thing that surprises me about Django, is that there does not seem to be any innovation to speak of regarding actual presentation. All the innovation would concern database issues, business logic, reusability of code, etc - but not actually anything new regarding innovative visual controls or graphics for a web-site. When you build a Django view or template, it will still be making extensive reference to html from what I can see (And presumably also Javascript - but I haven't actually even seen any Javascript in Django templates yet.)
And I would have thought previously that html might be analagous to assembler, so a conventional application developer from years past might know and occasionally even use a little assembler, but generally would hardly ever use it, whereas from what I can see, html (and also CSS and javascript) still have to be mastered and written continually by every web developer, whether they're using Django or anything else. Is that a true statement?
There is one site in particular that would to me as an end user represent the state of the art for web sites and I would be curious as to what the foundations of such a site might be. That site is chess.com, and there are all sorts of facilities for playing chess online with other users, user customization of their account with various graphical effects and so on. Is it most likely Java applets they're using for a site like that? How relevant would Django be for a such a site. Would Django be used in conjunction with something like Flash or even Java applets? Also when a site like chess.com is ported to a mobile device, what is used to write it - the same development tools as for the desktop or something completely different (Yes, I have a lot of catching up to do.)
Are there in fact complete websites written solely in Java, perhaps using very high level Java API's? Why would someone say (as I read somewhere) that they despised Java so that is why they had gotten into Ruby on Rails and Django.
And regarding Python (and also PHP) what is the justification for their existence? First of all, Python is much, much slower than say C++, being interpreted. Why are websites written in Python or PHP - is platform independence the sole issue here. I am incredulous that application development is much faster in Python than C++ (aside from the garbage collection issue - is that what the primary reason for Python is - garbage collection.)
So anyway, a bunch of newbie questions - will probably end up answering most of them myself if they're not answered here. Maybe they're relevant to someone else though.
A:
Hmm, you've asked a laundry list of questions here. I'll pick a couple of the important ones and answer.
As for the rationale for languages like Python... the truth is that many web applications are either I/O bound or database bound. When that's the case it doesn't matter much if the language you're using is not as fast as C++- the bottleneck is elsewhere. Beyond that an awful lot of the core Python routines and data structures are written in C. Python is used to drive the highest level of logic, but most of the work happens in fast native code. It might surprise you to learn that in my current job I write 3D animation software in Python. Of course a lot of what is going on behind the scenes was written in C++. There's a name for this: "Alternate Hard and Soft Layers." The reason we use Python is pretty simple- our choices are Python or C++ because of the APIs we write to, and we're several times as productive in Python. I would actually ask what the rationale for the existence of C++ is, but that's another subject (and flamebait ;).)
As for the visual presentation issues... traditionally there has been a pretty distinct separation between the server-side logic of an application and the in-browser logic, partially because the only language you can count on being in the browser is Javascript (and even then you can't actually count on it being on, leaving aside the existence of browsers like Lynx.) So you wrote your server logic in some sort of framework like Django, and then you used some Javascript framework to do your front-end stuff, and (in the last few years) you used something like AJAX to let them interoperate a bit more smoothly.
This is still pretty much the dominant paradigm, but things have started to change. A lot of server-side frameworks have started including facilities for generating Javascript in one way or another. And people have started writing compilers that translate from other languages to Javascript. One prominent example is Google's GWT, which translates from Java to Javascript: http://code.google.com/webtoolkit/ There are other examples of this sort of approach though. I did a lot of programming in a common lisp library called parenscript ( http://common-lisp.net/project/parenscript/) a few years ago, and there is the beginning of a Clojure ( http://clojure.org/) library for doing something similar. Also, one of the most interesting set of frameworks around is Seaside/Magritte ( http://www.seaside.st/ and http://www.lukas-renggli.ch/smalltalk/magritte) which use continuations to manage the state of widgets. There are similar frameworks for scheme and common lisp.
As for html being like assembler, I'm inclined to agree in cases where I am writing the html. I tend to use some sort of abstraction layer to generate html in those cases. But an awful lot of the html in the world is made by designers. Some of them use GUI applications to generate html, and the better ones use text editors. But most of them don't want to deal with anything more complicated than simple templating in html, which is what they know.
One thing you have to understand about the evolution of the web is that http and html were not initially designed to do the kinds of things they are being used for today. And on top of that the major browsers have very often been really broken. And on top of that you have no control over what facilities the user has available to them- they could be using any browser, with or without Java, Javascript, Flash, etc, and with any of a number of permutations of bugsets, depending on the browser. So it's only in the last several years that things have stabilized enough for people to be a little less conservative about the facilities they use on the client side. It's still a good idea to make sure that pages degrade gracefully, when possible. A general purpose web page should be usable in a text browser, though of course many types of web applications can't be made to work in that limited an environment.
HTML 5 is going to shake a lot of this up. But it is going to be a long time before it is safe to assume that everyone is using a browser capable of doing anything from HTML 5, and longer before it is safe to assume that everyone is using a browser that implements all of HTML 5. Anyway, I'd suggest you look around at some of the less visible projects, like Seaside for instance. There is a lot of experimentation going on. But the web has always been a tough environment for this kind of thing.
A:
Django wasn't trying to innovate in how web sites are displayed in the browser. Their goal was to simplify the process of building a web site. They could have taken on new ways of creating widgets in the browser as part of that goal, but they didn't. There was plenty of pain to relieve in the classic construction of websites.
If you are building web sites, you will be dealing with HTML. Your analogy to assembler is interesting, but in that analogy, no popular higher-level languages have emerged. This is likely because every higher-level language would of necessity impose some constraints on what could be expressed, and the web is not at the point of wanting conformity like that.
Python is an easier-to-use language than C++, and you really can develop faster in it. You should try it. Automatic memory management is one reason, but others are easy-to-use data structures, not having to ask permission from the compiler to do what you want, extensive third-party libraries to build on, and a clutter-free language in which to express yourself. About the speed: web sites are not compute-bound, they are I/O-bound, so the speed of the language rarely makes a difference.
About the ad-hoc nature of web development. You're coming from a Windows development background, where one vendor defined the entire environment, and did a good job of it. Web development is ad-hoc because the web itself is ad-hoc. No one group defined it, it's grown organically with contributions from many.
A:
All the innovation would concern database issues, business logic, reusability of code, etc - but not actually anything new regarding innovative visual controls or graphics for a web-site
Correct. Good assessment. Is that a problem?
html might be analagous to assembler, so a conventional application developer from years past might know and occasionally even use a little assembler, but generally would hardly ever use it
False. Indeed, not even close. All browsers uses HTML. That cannot be changed easily.
chess.com... Is it most likely Java applets they're using for a site like that?
Use view source in your browser to answer this question for yourself. In general, you should do this for every web site you visit. You'll learn a great deal about the web and web development.
Would Django be used in conjunction with something like Flash or even Java applets
Yes. We use FLEX and Django.
Also when a site like chess.com is ported to a mobile device, what is used to write it - the same development tools as for the desktop or something completely different (Yes, I have a lot of catching up to do.)
Yes.
Are there in fact complete websites written solely in Java, perhaps using very high level Java API's?
Yes.
Why would someone say (as I read somewhere) that they despised Java so that is why they had gotten into Ruby on Rails and Django.
Some people like to despise Java. There's little technical merit to their argument.
After you've used Java and Python, you'll find that Python's less wordy. You get more done with less typing.
what is the justification for their [Python PHP] existence?
They're better than the alternatives. For specific things people need to do, Python (or PHP) are better than the alternatives. For "everything" or even a broad class of things, it may not be perfectly clear.
We do a lot of ad-hoc data crunching. Python's flexibility is absolutely superior to the alternatives.
First of all, Python is much, much slower than say C++, being interpreted.
That's hardly relevant, it turns out. Web sites are not governed by raw speed of one element of the architecture.
Why are websites written in Python or PHP
It's easier than the alternatives.
is platform independence the sole issue here.
No.
I am incredulous that application development is much faster in Python than C++
Have you done much with Python? You should give it a try for a year or so. It makes C++ quite tedious and error-prone by comparison.
is that what the primary reason for Python is - garbage collection.
No.
A:
And I would have thought previously that html might be analagous to assembler, so a conventional application developer from years past might know and occasionally even use a little assembler, but generally would hardly ever use it, whereas from what I can see, html (and also CSS and javascript) still have to be mastered and written continually by every web developer, whether they're using Django or anything else. Is that a true statement?
Yup — if you want a website, someone’s going to have to write some HTML.
HTML is unlike assembler in that you can’t write parsers for new languages in HTML. HTML is just a declarative language for adding meaning to text. As such, the main thing is that everyone in the world agrees how how to render it, and what the tags mean. Something new might replace it eventually, but HTML has proven pretty serviceable and resilient so far. It’s also pretty easy to learn, and free.
Is it most likely Java applets they're using for a site like that? How relevant would Django be for a such a site. Would Django be used in conjunction with something like Flash or even Java applets?
Django really just concerns itself with the server side of websites. It leaves the client side of things (i.e. whatever runs in the browser) up to you. (Aside from the built-in admin site.)
Are there in fact complete websites written solely in Java, perhaps using very high level Java API's?
I don’t think it’s common. Java applets are hardly used any more, and some people (cough Steve Jobs cough sorry about the cough there, I said “Steve Jobs”) think Flash will go the same way.
A:
In addition to everything everyone else have said so far, just making a very basic web site with HTML, some CSS and maybe even some JavaScript will probably give you a decent understanding of how those three work. A place like HTMLDog is a good place to start.
In addition, read up a little on the HTTP-protocol as this is still what normal web pages use and therefore defines the basics of how servers and clients communicate on the web.
HTTP, HTML, CSS and JavaScript is (and will probably be for quite a while) the same wheather you use Java, Django, ASP.NET or PHP for your application logic. If you are getting more into web development, these are relevant no matter what server-side technology you would ever choose. Also, a general understanding of browsers is nice to have. Both how they handle the visual rendering of HTML and CSS, but also how sessions, cookies and requests are handled.
A:
The javascript stuff might look daunting, but nowadays there are pretty decent libraries that are Free/OSS, most notably jquery. I consider jquery to be partly a replacement for Flash.
You don't need that much extra javascript to use it productively. I'd definitely use jquery if I had to make an interface like chess.com uses.
see www.jquery.com and www.jqueryui.com
A:
From what I read, ROR tries to do everything for you behind the scenes and so therefore is slow and unscalable (and overhyped and not ready for prime time).
Well, first of all, you shouldn't believe everything you read on the Internet:
I wouldn't say RoR isn't ready for primetime. RoR, like any tool, has its uses. If you're building a site like Twitter, maybe Rails isn't the best tool (as Twitter found out). While everyone thinks they're building a high-performance site, most developers aren't, and Rails will probably be suitable. Furthermore, Rails can scale, and a lot of work has been done to improve that situation even more.
The reason Rails sometimes has performance issues is not because it tries to do everything for you -- it's more because of the nature of the Ruby interpreter itself, which (until Ruby 1.9) was rather slow, and still isn't even as fast as other interpreted languages.
And the first thing that surprises me about Django, is that there does not seem to be any innovation to speak of regarding actual presentation. All the innovation would concern database issues, business logic, reusability of code, etc - but not actually anything new regarding innovative visual controls or graphics for a web-site.
Yes, but that is the innovation. Prior to frameworks like Django and Rails, a lot of that backend work was done by hand. Django frees up a developer's time to work on more application-level features.
And I would have thought previously that html might be analagous to assembler, so a conventional application developer from years past might know and occasionally even use a little assembler, but generally would hardly ever use it, whereas from what I can see, html (and also CSS and javascript) still have to be mastered and written continually by every web developer, whether they're using Django or anything else. Is that a true statement?
Yeah, pretty much. Nothing better than HTML, CSS, and JS has presented itself. While I agree that in some ways, HTML seems "low-level" in the same sense that assembly language is low-level, I think most would agree that, relative to problem domain, HTML is much nicer to work with.
Would Django be used in conjunction with something like Flash or even Java applets?
You can. Flash and Java are just embedded in HTML pages, and Django spits out HTML, so that's certainly possible.
Are there in fact complete websites written solely in Java, perhaps using very high level Java API's? Why would someone say (as I read somewhere) that they despised Java so that is why they had gotten into Ruby on Rails and Django.
In addition to applets, you can write a backend in Java (Java Server Pages, for example). I think most web developers who have worked with both would agree than Ruby and Python are much nicer to use than Java. Java web frameworks are kind of a pain, Java lacks a REPL, Java has a separate compilation step... Java is also statically typed; you can argue all day about the merits of dynamic typing vs. static typing, but Rails and Django both take advantage of Ruby's and Python's typing and introspection capabilities to make a lot of code less verbose than that of Java. (Whether that makes Ruby and Python better than Java is subjective.)
And regarding Python (and also PHP) what is the justification for their existence? First of all, Python is much, much slower than say C++, being interpreted. Why are websites written in Python or PHP - is platform independence the sole issue here. I am incredulous that application development is much faster in Python than C++ (aside from the garbage collection issue - is that what the primary reason for Python is - garbage collection.)
Performance isn't everything. Almost everyone wants to think their code is performance critical, but that's often not the case. As noted in a few other answers, most web apps are I/O bound anyway -- they're either waiting for database access, or waiting on the network, and both of those types of operations are orders of magnitude slower than CPU-intensive tasks, even with slow(er) interpreted languages. Furthermore, a lot of processing in web apps takes place on strings, and string processing is much nicer in Python or Ruby than it is in, e.g., C or C++. Python and Ruby are also more concise languages, and both offer a REPL which can shorten development time. Plus it's easy to write C extension modules in both Python and Ruby, so if you really, really find a code path that calls out for optimization, you can always drop down into C if you want.
Garbage collection is a plus, though.
A:
And I would have thought previously that html might be analagous to assembler, so a conventional application developer from years past might know and occasionally even use a little assembler, but generally would hardly ever use it, whereas from what I can see, html (and also CSS and javascript) still have to be mastered and written continually by every web developer, whether they're using Django or anything else. Is that a true statement?
That's why I use Seaside. You still have to understand html and css and javascript, but at least there is a programming language abstraction over html. I'll never go back to a template based system.
| Big picture questions regarding Django, Java, Python, HTML and web-site development in general | I am trying to get a handle on the state of the art regarding web site development and have several questions. Maybe I'll end up finding most of the answers on my own. I come from a background of C++ and Windows development, and generally I am befuddled by what seems to be the ad-hoc nature of web development.
I focussed in on Django, after online research of it and Ruby (on Rails). From what I read, ROR tries to do everything for you behind the scenes and so therefore is slow and unscalable (and overhyped and not ready for prime time). So I have gotten into Django - downloaded Python and Django, the source from a complete Django site, got it running, and so forth.
And the first thing that surprises me about Django, is that there does not seem to be any innovation to speak of regarding actual presentation. All the innovation would concern database issues, business logic, reusability of code, etc - but not actually anything new regarding innovative visual controls or graphics for a web-site. When you build a Django view or template, it will still be making extensive reference to html from what I can see (And presumably also Javascript - but I haven't actually even seen any Javascript in Django templates yet.)
And I would have thought previously that html might be analagous to assembler, so a conventional application developer from years past might know and occasionally even use a little assembler, but generally would hardly ever use it, whereas from what I can see, html (and also CSS and javascript) still have to be mastered and written continually by every web developer, whether they're using Django or anything else. Is that a true statement?
There is one site in particular that would to me as an end user represent the state of the art for web sites and I would be curious as to what the foundations of such a site might be. That site is chess.com, and there are all sorts of facilities for playing chess online with other users, user customization of their account with various graphical effects and so on. Is it most likely Java applets they're using for a site like that? How relevant would Django be for a such a site. Would Django be used in conjunction with something like Flash or even Java applets? Also when a site like chess.com is ported to a mobile device, what is used to write it - the same development tools as for the desktop or something completely different (Yes, I have a lot of catching up to do.)
Are there in fact complete websites written solely in Java, perhaps using very high level Java API's? Why would someone say (as I read somewhere) that they despised Java so that is why they had gotten into Ruby on Rails and Django.
And regarding Python (and also PHP) what is the justification for their existence? First of all, Python is much, much slower than say C++, being interpreted. Why are websites written in Python or PHP - is platform independence the sole issue here. I am incredulous that application development is much faster in Python than C++ (aside from the garbage collection issue - is that what the primary reason for Python is - garbage collection.)
So anyway, a bunch of newbie questions - will probably end up answering most of them myself if they're not answered here. Maybe they're relevant to someone else though.
| [
"Hmm, you've asked a laundry list of questions here. I'll pick a couple of the important ones and answer.\nAs for the rationale for languages like Python... the truth is that many web applications are either I/O bound or database bound. When that's the case it doesn't matter much if the language you're using is not... | [
12,
10,
7,
2,
1,
1,
1,
1
] | [] | [] | [
"django",
"html",
"java",
"mobile",
"python"
] | stackoverflow_0003345916_django_html_java_mobile_python.txt |
Q:
Custom class instance copying
I'm new to programming and Python. The problem I have is with removing list elements that are instances of custom class.
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
z.remove(zcopy[0])
This returns:
ValueError: list.remove(x): x not in list
Is there a simple way to remove element from list by using reference from deepcopied list?
edit: Thanks for your answers. I found some solution using indexing. It's not pretty but it does the job:
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
del z[zcopy.index(zcopy[0])]
A:
No, because the call to deepcopy creates a copy of the some_class instance. That copy, zcopy[0] is a different object from the original, z[0], so when you try to remove zcopy[0] from the list z, it rightly complains that the copy doesn't exist in the original list. Furthermore, there is no link between the copied object and the original object, which is the intent of deepcopy.
I suppose you could implement a __deepcopy__ method in your class, which returns a copy that maintains some reference to the original object. Then you could use that reference to get the original object, z[0], from the copy, zcopy[0]. It strikes me as a rather odd thing to do, though, and probably not a good idea. Without further information, I'd suggest just using copy.copy instead of copy.deepcopy.
| Custom class instance copying | I'm new to programming and Python. The problem I have is with removing list elements that are instances of custom class.
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
z.remove(zcopy[0])
This returns:
ValueError: list.remove(x): x not in list
Is there a simple way to remove element from list by using reference from deepcopied list?
edit: Thanks for your answers. I found some solution using indexing. It's not pretty but it does the job:
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
del z[zcopy.index(zcopy[0])]
| [
"No, because the call to deepcopy creates a copy of the some_class instance. That copy, zcopy[0] is a different object from the original, z[0], so when you try to remove zcopy[0] from the list z, it rightly complains that the copy doesn't exist in the original list. Furthermore, there is no link between the copied ... | [
1
] | [] | [] | [
"deep_copy",
"python"
] | stackoverflow_0003452691_deep_copy_python.txt |
Q:
Can Cherokee serve a fallback/default page when a reverse proxy is unavailable?
I have a Cherokee installation that I'm using to serve a few web applications - one blog/calendar/etc. and two CPU-intensive web applications (1 stable version and 1 development version). All of them are Django or Pylons webservices served with CherryPy. I'm using the reverse-proxy handler in Cherokee to handle the mappings.
Occasionally I have to take the development version down to make changes. Is there a way to set up Cherokee so that it will automatically serve (or redirect to) another page (e.g. indicating an under-construction status) when the reverse-proxy target is unfindable or unresponsive?
I'd prefer an automated solution in Cherokee but if someone knows a simple point-and-click method I'll take that too.
A:
You could set a custom 504 error page.
| Can Cherokee serve a fallback/default page when a reverse proxy is unavailable? | I have a Cherokee installation that I'm using to serve a few web applications - one blog/calendar/etc. and two CPU-intensive web applications (1 stable version and 1 development version). All of them are Django or Pylons webservices served with CherryPy. I'm using the reverse-proxy handler in Cherokee to handle the mappings.
Occasionally I have to take the development version down to make changes. Is there a way to set up Cherokee so that it will automatically serve (or redirect to) another page (e.g. indicating an under-construction status) when the reverse-proxy target is unfindable or unresponsive?
I'd prefer an automated solution in Cherokee but if someone knows a simple point-and-click method I'll take that too.
| [
"You could set a custom 504 error page.\n"
] | [
0
] | [] | [] | [
"cherokee",
"python",
"reverse_proxy",
"web_services"
] | stackoverflow_0003449673_cherokee_python_reverse_proxy_web_services.txt |
Q:
Boost Python (Suse and Ubuntu)
I created a simple .so library containing definition of a C++ class which should be accessed from Python and used for this purpose boost python library.
When I'm testing this library using x64 Ubuntu it is enough to set LD_LIBRARY_PATH with the path to boost libs before running python. It doesn't work, however, when I'm using x64 Suse.
Altough I'm setting LD_LIBRARY_PATH it seems that Python ignores it.
Is there any specific way to set environmental variables under Suse?
A:
You should never set LD_LIBRARY_PATH, see here and here.
First of all I have to assume that you installed the Boost libraries in a nonstandard location, otherwise the loader would find them automatically. If you have root access to the machine, install the libraries in a standard place (e.g. with the package manager, or in /usr/local/lib).
If you don't have root privileges, set the runpath instead. When using the gcc linker, do this by passing an -rpath option. The gcc compiler can pass options to the linker via -Wl. So call the compiler as follows:
g++ -Wall -Wextra -Wl,-rpath /path/to/boost -L /path/to/boost -lboost_python ...
| Boost Python (Suse and Ubuntu) | I created a simple .so library containing definition of a C++ class which should be accessed from Python and used for this purpose boost python library.
When I'm testing this library using x64 Ubuntu it is enough to set LD_LIBRARY_PATH with the path to boost libs before running python. It doesn't work, however, when I'm using x64 Suse.
Altough I'm setting LD_LIBRARY_PATH it seems that Python ignores it.
Is there any specific way to set environmental variables under Suse?
| [
"You should never set LD_LIBRARY_PATH, see here and here.\nFirst of all I have to assume that you installed the Boost libraries in a nonstandard location, otherwise the loader would find them automatically. If you have root access to the machine, install the libraries in a standard place (e.g. with the package mana... | [
0
] | [] | [] | [
"boost",
"c++",
"python",
"suse",
"ubuntu"
] | stackoverflow_0003452505_boost_c++_python_suse_ubuntu.txt |
Q:
Respond to Listctrl change exactly once
I'm working on a form using wxPython where I want want listctrl's list of values to change based on the selection of another listctrl. To do this, I'm using methods linked to the controlling object's EVT_LIST_ITEM_SELECTED and EVT_LIST_ITEM_DESELECTED events to call Publisher.sendMessage. The control to be changed has a method that is a subscriber to that publisher. This works: when the first listctrl is clicked, the second is refreshed.
The problem is that the data must be refreshed from the database and a message is sent for every selection and deselection. This means that even if I simply click on one item, the database gets queried twice (once for the deselection, then again for the selection). If I shift-click to multi-select 5 items, then 5 calls get made. Is there any way to have the listctrl respond to the set, rather than the individual selections?
A:
The best solution seems to be to use wx.CallAfter with a flag to execute the follow-up procedure exactly once:
import wx
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
self.list_ctrl_1.InsertColumn(0,"1")
self.list_ctrl_1.InsertStringItem(0,"HELLO1")
self.list_ctrl_1.InsertStringItem(0,"HELLO2")
self.list_ctrl_1.InsertStringItem(0,"HELLO3")
self.list_ctrl_1.InsertStringItem(0,"HELLO4")
self.list_ctrl_1.InsertStringItem(0,"HELLO5")
self.list_ctrl_1.InsertStringItem(0,"HELLO6")
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.list_ctrl_1)
self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected, self.list_ctrl_1)
self.dirty = False
def Cleanup(self, StringToPrint):
print 'No Longer Dirty!'
self.dirty = False
def OnItemSelected(self,event):
print str(self.__class__) + " - OnItemSelected"
if not self.dirty:
self.dirty = True
wx.CallAfter(self.Cleanup)
event.Skip()
def OnItemDeselected(self,event):
print str(self.__class__) + " - OnItemDeselected"
if not self.dirty:
self.dirty = True
wx.CallAfter(self.Cleanup)
event.Skip()
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
A:
You can try EVT_LIST_ITEM_RIGHT_CLICK. That should work. Otherwise you'd want to use a flag and check said flag every time the selection event fires to see if it needs to query the database or not. There's also the UltimateListCtrl, a pure python widget, that you can probably hack to do this too.
A:
You can push in a custom event handler
import wx
class MyEventHandler(wx.PyEvtHandler):
def __init__(self,target):
self.target = target
wx.PyEvtHandler.__init__(self)
def ProcessEvent(self,event):
# there must be a better way of getting the event type,
# but I couldn't find it
if event.GetEventType() == wx.EVT_LEFT_DOWN.evtType[0]:
print "Got Mouse Down event"
(item,where) = self.target.HitTest(event.GetPosition())
if item != -1:
print self.target.GetItem(item,0).GetText()
print where
else:
print "Not on list item though"
return True
else:
return False
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.myevthandler = MyEventHandler(self.list_ctrl_1)
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
self.list_ctrl_1.InsertColumn(0,"1")
self.list_ctrl_1.InsertStringItem(0,"HELLO1")
self.list_ctrl_1.PushEventHandler(self.myevthandler)
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
| Respond to Listctrl change exactly once | I'm working on a form using wxPython where I want want listctrl's list of values to change based on the selection of another listctrl. To do this, I'm using methods linked to the controlling object's EVT_LIST_ITEM_SELECTED and EVT_LIST_ITEM_DESELECTED events to call Publisher.sendMessage. The control to be changed has a method that is a subscriber to that publisher. This works: when the first listctrl is clicked, the second is refreshed.
The problem is that the data must be refreshed from the database and a message is sent for every selection and deselection. This means that even if I simply click on one item, the database gets queried twice (once for the deselection, then again for the selection). If I shift-click to multi-select 5 items, then 5 calls get made. Is there any way to have the listctrl respond to the set, rather than the individual selections?
| [
"The best solution seems to be to use wx.CallAfter with a flag to execute the follow-up procedure exactly once:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwds):\n wx.Frame.__init__(self, *args, **kwds)\n self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKE... | [
4,
0,
0
] | [] | [] | [
"listctrl",
"python",
"wxpython"
] | stackoverflow_0003441991_listctrl_python_wxpython.txt |
Q:
How to customize wx.ProgressDialog?
Is it possible to customize ProgressDialog in wxPython?
For instance, I would like to make the progressbar slimmer, and the window size wider.
SetSize() method doesn't appear to have any effect.
A:
The wx.ProgressDialog isn't customizable its just a wrapper around the native ProgressDialog, the the easiest solution would be to roll your own by extending the wx.Dialog class and using a wx.Gauge
| How to customize wx.ProgressDialog? | Is it possible to customize ProgressDialog in wxPython?
For instance, I would like to make the progressbar slimmer, and the window size wider.
SetSize() method doesn't appear to have any effect.
| [
"The wx.ProgressDialog isn't customizable its just a wrapper around the native ProgressDialog, the the easiest solution would be to roll your own by extending the wx.Dialog class and using a wx.Gauge\n"
] | [
1
] | [] | [] | [
"progress_bar",
"python",
"wxpython"
] | stackoverflow_0003452986_progress_bar_python_wxpython.txt |
Q:
Apply raw string to function return value
I'm not sure if I've phrased it correctly, but hopefully the example will clear it up:
re.search(fileMask.replace('*','.*?'),fileName):
For the first parameter in the re.search() call, how can I ensure that I will pass the value returned by the fileMask.replace() call as a raw string?
Something to the effect of:
re.search(r'fileMask.replace('*','.*?')',fileName):
..although that won't work because I actually need the fileMask function to be called.
A:
There is no such type as "a raw string" -- there are literals (of string types) that are so named, but the objects such literals stand for are string objects -- nothing more, nothing less. For example, literals r'a\b'' (a "raw string literal") and 'a\\b' (a normal string literal) represent exactly the same string value: one of length three, with characters a, backlash, and b, in this order. If you print these objects, both display as a\b; if you print their repr, it's a\\b in both cases.
So, it's hard to understand your question. Could you give examples of some possible values for fileMask and fileName, and the results you expect from the consequent re.search calls?
Also,
I actually need the fileMask function
to be called.
That might really be a problem, because there appears to be no function named fileMask, but rather (it would seem) a string thus named. Do you mean "need the method of fileMask to be called"?
A:
re.search(fileMask.replace('\*','\.\*?').encode('string_escape'), fileName):
| Apply raw string to function return value | I'm not sure if I've phrased it correctly, but hopefully the example will clear it up:
re.search(fileMask.replace('*','.*?'),fileName):
For the first parameter in the re.search() call, how can I ensure that I will pass the value returned by the fileMask.replace() call as a raw string?
Something to the effect of:
re.search(r'fileMask.replace('*','.*?')',fileName):
..although that won't work because I actually need the fileMask function to be called.
| [
"There is no such type as \"a raw string\" -- there are literals (of string types) that are so named, but the objects such literals stand for are string objects -- nothing more, nothing less. For example, literals r'a\\b'' (a \"raw string literal\") and 'a\\\\b' (a normal string literal) represent exactly the same... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003452925_python.txt |
Q:
Rename config.ini section using ConfigParser in python
Is there an easy way to rename a section in a config file using ConfigParser in python? I'd prefer not to have to delete the section and recreate it, but that is my only answer right now.
A:
No. The builtin ConfigParser stores sections as _sections, which is a dict. Since this is python you could access that variable to do an easy copy.
(config._sections[new_name] = config._sections[old_name]; config._sections.pop(old_name)
But ConfigParser may change at some later date and this would break your implementation.
Therefore I don't recommend doing that, alternatively you could subclass ConfigParser and implement a delete_section or change the way options are stored.
| Rename config.ini section using ConfigParser in python | Is there an easy way to rename a section in a config file using ConfigParser in python? I'd prefer not to have to delete the section and recreate it, but that is my only answer right now.
| [
"No. The builtin ConfigParser stores sections as _sections, which is a dict. Since this is python you could access that variable to do an easy copy. \n(config._sections[new_name] = config._sections[old_name]; config._sections.pop(old_name) \nBut ConfigParser may change at some later date and this would break your i... | [
0
] | [] | [] | [
"config",
"configparser",
"python"
] | stackoverflow_0003452788_config_configparser_python.txt |
Q:
BeautifulSoup doesn't give me Unicode
I'm using Beautiful soup to scrape data. The BS documentation states that BS should always return Unicode but I can't seem to get Unicode. Here's a code snippet
import urllib2
from libs.BeautifulSoup import BeautifulSoup
# Fetch and parse the data
url = 'http://wiki.gnhlug.org/twiki2/bin/view/Www/PastEvents2007?skin=print.pattern'
data = urllib2.urlopen(url).read()
print 'Encoding of fetched HTML : %s', type(data)
soup = BeautifulSoup(data)
print 'Encoding of souped up HTML : %s', soup.originalEncoding
table = soup.table
print type(table.renderContents())
The original data returned from the page is a string. BS shows the original encoding as ISO-8859-1. I thought that BS automatically converted everything to Unicode so why is it that when I do this:
table = soup.table
print type(table.renderContents())
..it gives me a string object and not Unicode?
How can i get a Unicode objects from BS?
I'm really, really lost with this. Any help? Thanks in advance.
A:
As you may have noticed renderContent returns (by default) a string encoded in UTF-8, but if you really want a Unicode string representing the entire document you can also do unicode(soup) or decode the output of renderContents/prettify using unicode(soup.prettify(), "utf-8").
Related
How to render contents of a tag in unicode in BeautifulSoup?
A:
originalEncoding is exactly that - the source encoding, so the fact that BS is storing everything as unicode internally won't change that value. When you walk the tree, all text nodes are unicode, all tags are in unicode, etc., unless you otherwise convert them (say by using print, str, prettify, or renderContents).
Try doing something like:
soup = BeautifulSoup(data)
print type(soup.contents[0])
Unfortunately everything else you've done up to this point has found the very few methods in BS that convert to strings.
| BeautifulSoup doesn't give me Unicode | I'm using Beautiful soup to scrape data. The BS documentation states that BS should always return Unicode but I can't seem to get Unicode. Here's a code snippet
import urllib2
from libs.BeautifulSoup import BeautifulSoup
# Fetch and parse the data
url = 'http://wiki.gnhlug.org/twiki2/bin/view/Www/PastEvents2007?skin=print.pattern'
data = urllib2.urlopen(url).read()
print 'Encoding of fetched HTML : %s', type(data)
soup = BeautifulSoup(data)
print 'Encoding of souped up HTML : %s', soup.originalEncoding
table = soup.table
print type(table.renderContents())
The original data returned from the page is a string. BS shows the original encoding as ISO-8859-1. I thought that BS automatically converted everything to Unicode so why is it that when I do this:
table = soup.table
print type(table.renderContents())
..it gives me a string object and not Unicode?
How can i get a Unicode objects from BS?
I'm really, really lost with this. Any help? Thanks in advance.
| [
"As you may have noticed renderContent returns (by default) a string encoded in UTF-8, but if you really want a Unicode string representing the entire document you can also do unicode(soup) or decode the output of renderContents/prettify using unicode(soup.prettify(), \"utf-8\").\nRelated\n\nHow to render contents ... | [
5,
2
] | [] | [] | [
"beautifulsoup",
"character_encoding",
"python",
"unicode"
] | stackoverflow_0003192645_beautifulsoup_character_encoding_python_unicode.txt |
Q:
How to dynamically create directories and output files into them python
I have a python script that is trying to create a directory tree dynamically depending on the user input. This is what my code looks like so far.
if make_directories:
os.makedirs(outer_dir)
os.chdir(outer_dir)
for car in cars:
os.makedirs(car)
os.chdir(car)
#create a bunch of text files and do other stuff,
os.chdir('../')
os.chdir('../')
I was wondering if there was a better way to do this? I don't know if this is bad convention to keep changing directories like this.
Note: Cars is a list of car names that the user provides, outer_dir is a directory name that is also provided by the user
A:
I tend to do path manipulations rather than changing directories; just because the current directory is a bit of "implied state" whereas the paths can be explicity rooted.
if make_directories:
for car in cars:
carpath = os.path.join(outer_dir, car)
os.makedirs(carpath)
for fn in textfiles:
filepath = os.path.join(carpath, fn)
#... use filepath ...
| How to dynamically create directories and output files into them python | I have a python script that is trying to create a directory tree dynamically depending on the user input. This is what my code looks like so far.
if make_directories:
os.makedirs(outer_dir)
os.chdir(outer_dir)
for car in cars:
os.makedirs(car)
os.chdir(car)
#create a bunch of text files and do other stuff,
os.chdir('../')
os.chdir('../')
I was wondering if there was a better way to do this? I don't know if this is bad convention to keep changing directories like this.
Note: Cars is a list of car names that the user provides, outer_dir is a directory name that is also provided by the user
| [
"I tend to do path manipulations rather than changing directories; just because the current directory is a bit of \"implied state\" whereas the paths can be explicity rooted. \nif make_directories:\n for car in cars:\n carpath = os.path.join(outer_dir, car)\n os.makedirs(carpath)\n for fn in... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003453329_python.txt |
Q:
TimeUUID with Cassandra and Lazyboy
I try to insert column with UUID1 keys to be able to sort them by date. I always get the error "cassandra.ttypes.InvalidRequestException: InvalidRequestException(why='UUIDs must be exactly 16 bytes')", and I don't know why.
Here is the code generating this error :
from lazyboy import *
from lazyboy.key import Key
import uuid
class TestItemKey(Key):
def __init__(self, key=None):
Key.__init__(self, 'MXstore', 'TestCF', key)
class TestItem(record.Record):
def __init__(self, *args, **kwargs):
record.Record.__init__(self, *args, **kwargs)
self.key = TestItemKey(uuid.uuid1().bytes)
connection.add_pool('MXstore', ['localhost:9160'])
tmp = {'foo' : 'bar'}
tmps = TestItem(tmp).save()
What did I do wrong ? I use lazyboy 0.705 with Cassandra 0.6.4.
The storage configuration is :
<Keyspaces>
<Keyspace Name="MXstore">
<ColumnFamily Name="TestCF" CompareWith="TimeUUIDType" />
<ReplicaPlacementStrategy>org.apache.cassandra.locator.RackUnawareStrategy</ReplicaPlacementStrategy>
<ReplicationFactor>3</ReplicationFactor>
<EndPointSnitch>org.apache.cassandra.locator.EndPointSnitch</EndPointSnitch>
</Keyspace>
</Keyspaces>
A:
The column name must be of uuid version 1. Looks like your key is a uuid version 1
| TimeUUID with Cassandra and Lazyboy | I try to insert column with UUID1 keys to be able to sort them by date. I always get the error "cassandra.ttypes.InvalidRequestException: InvalidRequestException(why='UUIDs must be exactly 16 bytes')", and I don't know why.
Here is the code generating this error :
from lazyboy import *
from lazyboy.key import Key
import uuid
class TestItemKey(Key):
def __init__(self, key=None):
Key.__init__(self, 'MXstore', 'TestCF', key)
class TestItem(record.Record):
def __init__(self, *args, **kwargs):
record.Record.__init__(self, *args, **kwargs)
self.key = TestItemKey(uuid.uuid1().bytes)
connection.add_pool('MXstore', ['localhost:9160'])
tmp = {'foo' : 'bar'}
tmps = TestItem(tmp).save()
What did I do wrong ? I use lazyboy 0.705 with Cassandra 0.6.4.
The storage configuration is :
<Keyspaces>
<Keyspace Name="MXstore">
<ColumnFamily Name="TestCF" CompareWith="TimeUUIDType" />
<ReplicaPlacementStrategy>org.apache.cassandra.locator.RackUnawareStrategy</ReplicaPlacementStrategy>
<ReplicationFactor>3</ReplicationFactor>
<EndPointSnitch>org.apache.cassandra.locator.EndPointSnitch</EndPointSnitch>
</Keyspace>
</Keyspaces>
| [
"The column name must be of uuid version 1. Looks like your key is a uuid version 1\n"
] | [
1
] | [] | [] | [
"cassandra",
"python",
"uuid"
] | stackoverflow_0003450560_cassandra_python_uuid.txt |
Q:
Communicating multiple times with a subprocess
I'm trying to pipe input to a program opened as a subprocess in Python. Using communicate() does what I want, but it only does so once, then waits for the subprocess to terminate before allowing things to continue.
Is there a method or module similar to communicate() in function, but allows multiple communications with the child process?
Here's an example:
import subprocess
p = subprocess.Popen('java minecraft_server.jar',
shell=True,
stdin=subprocess.PIPE);
//Pipe message to subprocess console here
//Do other things
//Pipe another message to subprocess console here
If this can be done in an easier fashion without using subprocess, that would be great as well.
A:
You can write to p.stdin (and flush every time to make sure the data is actually sent) as many separate times as you want. The problem would be only if you wanted to be sure to get results back (since it's so hard to convince other processes to not buffer their output!-), but since you're not even setting stdout= in your Popen class that's clearly not a problem for you. (When it is a problem, and you really need to defeat the other process's output buffering strategy, pexpect -- or wexpect on Windows -- are the best solution -- I recommend them very, very often on stackoverflow, but don't have the URLs at hand right now, so pls just search for them yourself if, contrary to your example, you do have that need).
| Communicating multiple times with a subprocess | I'm trying to pipe input to a program opened as a subprocess in Python. Using communicate() does what I want, but it only does so once, then waits for the subprocess to terminate before allowing things to continue.
Is there a method or module similar to communicate() in function, but allows multiple communications with the child process?
Here's an example:
import subprocess
p = subprocess.Popen('java minecraft_server.jar',
shell=True,
stdin=subprocess.PIPE);
//Pipe message to subprocess console here
//Do other things
//Pipe another message to subprocess console here
If this can be done in an easier fashion without using subprocess, that would be great as well.
| [
"You can write to p.stdin (and flush every time to make sure the data is actually sent) as many separate times as you want. The problem would be only if you wanted to be sure to get results back (since it's so hard to convince other processes to not buffer their output!-), but since you're not even setting stdout=... | [
7
] | [] | [] | [
"communication",
"python",
"subprocess"
] | stackoverflow_0003453345_communication_python_subprocess.txt |
Q:
How to programmatically add bindings to the current class scope in Python?
Though the question is very specific, I'd also really appreciate general advice and other approaches that would make my question moot. I'm building a collection of AI programs, and many of the functions and classes need to deal with a lot of different states and actions that cause transitions between states, so I need a way to represent states and actions. Please note that I'm not building a simple state machine, but rather a number of different programs (agents) that all take states and return actions as a way of interacting with an environment.
I could use strings, but that's messy if a particular algorithm needs to associate additional information with a state or action, and comparing strings over and over again in long-running programs is wasted overhead. The same sorts of problems arise with other kinds of constants. So my initial idea is to use nested classes, like so:
class DerivedAgent(Agent):
class StateA(State): pass
class StateB(State): pass
...
def do_something(state):
if state is self.StateA:
...
This works fairly well, but if there are a number of states and actions, it can take up a lot of space to declare them all, and all of the pass statements are annoying. I'd like to be able to do something like...
class DerivedAgent(Agent):
states("StateA", "StateB", "StateC", ...)
But I don't see a way to have the states method add the newly-created types to the DerivedAgent class. I think I might be able to do it with the inspect module, but that feels like it's going too far for a small convenience. Is using types like this a bad idea? Is there a much more elegant approach? Code outside of the agent classes will need to be able to access the states and actions, and putting states into the module namespace isn't a good option because a given module might have several agents in it.
A:
You could use meta classes so that you would end up with code like:
class DerivedAgent(Agent):
__states__ = ['StateA', 'StateB', ...]
for example:
class AgentMeta(type):
def __new__(meta, classname, bases, classdict):
for clsname in classdict['__states__']:
classdict[clsname] = type(clsname, (State,), {})
return type.__new__(meta, classname, bases, classdict))
then, just rewrite your Agent class so that it has the line
#python3.x
class Agent(Base1, Base2, ..., BaseN, metaclass=AgentMeta):
#everything else unchanged
# 2.2 <= python <= 2.7
class Agent(Base1, Base2, ..., BaseN):
__metaclass__ = AgentMeta
#everything else unchanged
If you don't want to change the Agent class, you can just include the approriate declaration of metaclass in each subclass of it that you create.
A:
Explicit state machines are boring, you can have implicit state machines in coroutines. But that is probably too much right now.
Anyways class StateA(State): pass is exactly the same as StateA = type("StateA", (State,), {}). Saves you typing the pass ;-)
A:
If you want a state machine, build one. A state machine is data-driven which means that the states and transitions are encoded as data, not class hierarchy.
In Python, dictionaries are the mechanism for ad hoc polymorphic dispatch:
def do_foo(**kwargs):
pass
def do_bar(**kwargs):
pass
dispatch = {
# state : { (transition, next_state) ... }
0: {'a' : (do_foo, 1)},
1: {'a' : (do_bar, 0)},
1: {'b' : (do_bar, None)}, # None -> accept
}
def state_machine(state, input):
"""does the action corresponding to state on input and returns new state"""
current = dispatch[state]
if input in current:
functor, next = current[input]
functor(lexeme=input)
return next
state = 0
for c in 'aaab':
state = state_machine(state, c)
if state is None:
print 'accepted'
break
| How to programmatically add bindings to the current class scope in Python? | Though the question is very specific, I'd also really appreciate general advice and other approaches that would make my question moot. I'm building a collection of AI programs, and many of the functions and classes need to deal with a lot of different states and actions that cause transitions between states, so I need a way to represent states and actions. Please note that I'm not building a simple state machine, but rather a number of different programs (agents) that all take states and return actions as a way of interacting with an environment.
I could use strings, but that's messy if a particular algorithm needs to associate additional information with a state or action, and comparing strings over and over again in long-running programs is wasted overhead. The same sorts of problems arise with other kinds of constants. So my initial idea is to use nested classes, like so:
class DerivedAgent(Agent):
class StateA(State): pass
class StateB(State): pass
...
def do_something(state):
if state is self.StateA:
...
This works fairly well, but if there are a number of states and actions, it can take up a lot of space to declare them all, and all of the pass statements are annoying. I'd like to be able to do something like...
class DerivedAgent(Agent):
states("StateA", "StateB", "StateC", ...)
But I don't see a way to have the states method add the newly-created types to the DerivedAgent class. I think I might be able to do it with the inspect module, but that feels like it's going too far for a small convenience. Is using types like this a bad idea? Is there a much more elegant approach? Code outside of the agent classes will need to be able to access the states and actions, and putting states into the module namespace isn't a good option because a given module might have several agents in it.
| [
"You could use meta classes so that you would end up with code like:\nclass DerivedAgent(Agent):\n __states__ = ['StateA', 'StateB', ...]\n\nfor example:\nclass AgentMeta(type):\n def __new__(meta, classname, bases, classdict):\n for clsname in classdict['__states__']:\n classdict[clsname] =... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003453058_python.txt |
Q:
Getting current url
I have a couple of views which are rendering the same template and I have some {% url %} tags into that template which needs to point to different location based on the current view. Is there any context variable which gives the name of the view(for named urls), like view-1 view-2, so in my template I can use it like this:
{% url url-name %}
It is also possible to pass additional information to the template so I can understand which view is called. But that would not be an elegant solution I guess.
A:
Pass RequestContext to the template renderer and write yourself a context processor to reconstruct the url from the request.
http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext
A:
I don't think there is any direct way in django to see which view rendered current template. So, it strips down, to either write a context processor (will increase complexity rather than reducing it) or send information from view.
But instead of sending view name to the template and making other locations based on that view, why not try sending the constructed url's from each view?? Decision logic is a lot more efficient in views rather than on django-templates. Just a suggestion.
Happy Coding.
A:
It is also possible to pass additional information to the template so I can understand which
view is called. But that would not be an elegant solution I guess.
Sure it is. Here's an example:
def view1(request, form_class=MyForm, template_name='myapp/page.html'):
# app code here
this_url = reverse('view1')
render_to_response(template_name, locals(), RequestContext(request))
def view2(request, form_class=MyForm, template_name='myapp/page.html'):
# app code here
this_url = reverse('view2')
render_to_response(template_name, locals(), RequestContext(request))
myapp/page.html:
<a href="{{ this_url }}">Webpage</a>
You can also create your own url tag called, say, dynurl that takes the first argument as a variable instead of as the view name:
def view2(request, form_class=MyForm, template_name='myapp/page2.html'):
# app code here
this_view = 'view2'
render_to_response(template_name, locals(), RequestContext(request))
myapp/page.html:
{% load dynurl_tags %}
<a href="{% dynurl this_view %}">Webpage</a>
You haven't exactly explained why you want a link to the current view, though. Is it in order to link to the same page? There are a couple of ways to do that:
<a href="">technically this points back to the same page</a>
<a href="{{ request.path }}">this url is the full path before the query string</a>
<a href="{{ request.get_full_path }}">this url is the full path plus the query string</a>
I think it would be useful to think about what the key differences are between the two views and come up with a variable that describes their difference. Then use that variable in the template to determine the new URLs.
For more complex problems you might want to look at Pinax groups and how they implement a {% groupurl %} tag. Basically it lets you duplicate all the urls of a given app and pass in a "group" variable that's used to create a special group-based reverse lookup for urls.
A:
Add django-debug-toolbar in development, when you need it. That shows you plenty of information about the current rendered page.
| Getting current url | I have a couple of views which are rendering the same template and I have some {% url %} tags into that template which needs to point to different location based on the current view. Is there any context variable which gives the name of the view(for named urls), like view-1 view-2, so in my template I can use it like this:
{% url url-name %}
It is also possible to pass additional information to the template so I can understand which view is called. But that would not be an elegant solution I guess.
| [
"Pass RequestContext to the template renderer and write yourself a context processor to reconstruct the url from the request.\nhttp://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext\n",
"I don't think there is any direct way in django to see which view rendered current template... | [
2,
1,
1,
0
] | [] | [] | [
"dispatcher",
"django",
"python",
"url"
] | stackoverflow_0003450903_dispatcher_django_python_url.txt |
Q:
Are Python 2.5 .pyc files compatible with Python 2.6 .pyc files?
A while ago I had to upgrade some servers from Python 2.4 to Python 2.5. I found that .pyc files created under Python 2.4 would crash when Python 2.5 tried to run them.
Will this happen again when I upgrade from 2.5 to 2.6?
EDIT: Here is a bit more detail
I have a fileserver that contains the python code. This is accessed by both Ubuntu and Windows servers to run the python code. When they run the code they produce .pyc files on the fileserver.
I found that when I upgraded one of the server machines from Python 2.4 to 2.5 I had problems with .pyc files. I'm now not sure whether it was a machine running 2.5 that tried to run 2.4 bytecode or whether it was a 2.4 machine trying to run 2.5 bytecode, but if I deleted the bytecode all went well until the next bytecode clash.
I upgraded all of the machines to 2.5 and the problem went away.
A:
In general, .pyc files are specific to one Python version (although portable across different machine architectures, as long as they're running the same version); the files carry the information about the relevant Python version in their headers -- so, if you leave the corresponding .py files next to the .pyc ones, the .pyc will be rebuilt every time a different Python version is used to import those modules. "Trying to run" wrong-version .pyc files is something I never heard about. What architectures were involved? Were the .py files around as they should be?
Edit: as the OP clarified that the crashes came when he was running both Python 2.4 and Python 2.5 programs on the same .py files (from two different servers, sharing a network drive), the explanation of the crashes becomes easy. The .py files were all the time being recompiled -- by the 2.4 Python when the 2.5 had been the one running them most recently, and vice versa -- and therefore the .pyc files were frantically busy getting rewritten all the time. Proper file locking on network drives (especially but not exclusively across different operating systems) is notoriously hard to achieve. So the following must have happened (the roles could be switched): the 2.4 server had just determined that a .pyc file was fine for it and started reading it; before it could finish reading, the 2.5 server (having previously determined that the module needed to be recompiled) wrote over it; so the 2.4 server ended up with a memory buffer that had (say) the first 4K bytes from the 2.4 version and the next 4K bytes from the 2.5 version. When it then used that mangled buffer, unsurprisingly... crash!!!
This can be a real problem if you ever find yourself continuously trying to run a single set of .py files from two or more different versions of Python (even on the same server, without the added complications of network drives). The "proper" solution would be something like virtualenv. The (simple, but dirty-ish) hack we adopted at work (many years ago, but it's still in production...!) is to patch each version of Python to produce and use a different extension for its compiled bytecode files: .pyc (or .pyo) for Python 1.5.2 (which was the most stable "system" version back when we started doing this kludge to newer versions), .pyc-2.0 for 2.0, .pyc-2.2 for 2.2, and so forth (or equivalent .pyo-X.Y of course). I hear this is soon going away at long last (thanks Thomas!-), but it did tide us semi-decently over this ticklish problem for many, many years.
A much simpler solution is to keep a single version of Python around, if that's feasible for your system; if your system has any complications that make it unfeasible to have a single Python version (as ours did, and does), then these days I'd heartily recommend virtualenv, which I've already mentioned.
With the adoption of PEP 3147 in Python 3.2, pyc files for different Python versions are distinguished automatically by filename. This should solve most problems with different Python versions overwriting each other's pyc files.
A:
If you have the source code then it will recompile it for you. So in general you are okay.
But, this could be bad for you if users with difference versions of Python run from a central installation directory.
It could also be bad if you just have the pyc files. I just ran a quick test for you. I created two .pyc files. One in 2.5 and one in 2.6. The 2.5 won't run in 2.6 and the 2.6 won't run in 2.5. Both throw "ImportError: Bad magic number in .." error, which makes sense because the magic number has changed from 2.5 to 2.6.
If you want to determine this ahead of time you can get the magic number of your Python as follows:
$ python -V
Python 2.6.2
# python
>>> import imp
>>> imp.get_magic().encode('hex')
'd1f20d0a'
To get the magic number for a pyc file you can do the following:
>>> f = open('test25.pyc')
>>> magic = f.read(4)
>>> magic.encode('hex')
'b3f20d0a'
>>> f = open('test26.pyc')
>>> magic = f.read(4)
>>> magic.encode('hex')
'd1f20d0a'
A:
The Python version that creates the file is stored in the .pyc file itself.
Usually this means that the .pyc is replaced by one with the correct Python version
some reasons this might not happen
- permissions
- .py file is not available
In the case of permission problem, Python will just use the .py and ignore the .pyc (at a cost to performance)
I think it is ok between minor versions though, eg a Python2.6.2 .pyc should work with Python2.6.4
Here is an excerpt from /usr/share/file/magic
# python: file(1) magic for python
0 string """ a python script text executable
0 belong 0x994e0d0a python 1.5/1.6 byte-compiled
0 belong 0x87c60d0a python 2.0 byte-compiled
0 belong 0x2aeb0d0a python 2.1 byte-compiled
0 belong 0x2ded0d0a python 2.2 byte-compiled
0 belong 0x3bf20d0a python 2.3 byte-compiled
0 belong 0x6df20d0a python 2.4 byte-compiled
0 belong 0xb3f20d0a python 2.5 byte-compiled
0 belong 0xd1f20d0a python 2.6 byte-compiled
So you can see that the correct Python version is indicated by the first 4 bytes of the .pyc file
A:
See http://www.python.org/dev/peps/pep-3149/ for a proposed fix for this (hopefully in Python 3.2)
A:
You will certainly need to recompile the bytecode files for them to be of any use. The bytecode magic number has changed over every major version of Python(*).
However, having non-version-matching bytecode files shouldn't ever crash Python. It will generally just ignore any bytecode that doesn't have the correct version number, so there shouldn't be an error, it'll just be slower the first time as it recompiles (or slower every time if the user running the scripts doesn't have write permission to update the bytecode).
(*: and often during the development phases, plus in earlier versions it sometimes changed over minor versions too. See import.c for a full list of magic numbers and their corresponding Python versions.)
| Are Python 2.5 .pyc files compatible with Python 2.6 .pyc files? | A while ago I had to upgrade some servers from Python 2.4 to Python 2.5. I found that .pyc files created under Python 2.4 would crash when Python 2.5 tried to run them.
Will this happen again when I upgrade from 2.5 to 2.6?
EDIT: Here is a bit more detail
I have a fileserver that contains the python code. This is accessed by both Ubuntu and Windows servers to run the python code. When they run the code they produce .pyc files on the fileserver.
I found that when I upgraded one of the server machines from Python 2.4 to 2.5 I had problems with .pyc files. I'm now not sure whether it was a machine running 2.5 that tried to run 2.4 bytecode or whether it was a 2.4 machine trying to run 2.5 bytecode, but if I deleted the bytecode all went well until the next bytecode clash.
I upgraded all of the machines to 2.5 and the problem went away.
| [
"In general, .pyc files are specific to one Python version (although portable across different machine architectures, as long as they're running the same version); the files carry the information about the relevant Python version in their headers -- so, if you leave the corresponding .py files next to the .pyc ones... | [
17,
6,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002263356_python.txt |
Q:
Convert 12hr date/time string to 24hr datetime
Like other questions asked here, im looking to do a simple conversion of time formats. I've found answers on how to do this in Perl, but not in Python.
I have a string like so:
on Jun 03, 02010 at 10:22PM
and I'd like to convert it to a datetime object like this:
Thu, 03 Jun 2010 22:22:00 -0000
I have sliced up my input like so:
date = str(comment.div.contents[5].contents)
month = date[6:9]
day = date[10:12]
year = date[15:19]
time = date[23:30]
which sets me up with some nice variables I can throw back into datetime but before I so, I must convert the time. Should I divide up time in the example above and calculate the hh and {AM|PM} separately?
A:
Using dateutil:
import datetime as dt
import dateutil.parser as dparser
date_str='on Jun 03, 02010 at 10:22PM'
date=dparser.parse(date_str)
print(date)
# 2010-06-03 22:22:00
print(date.strftime('%a, %d %b %Y %H:%M:%S'))
# Thu, 03 Jun 2010 22:22:00
If you can somehow strip out the pesky 'on' and change 02010 to 2010, in date_str then you could use dt.datetime.strptime:
date_str='Jun 03, 2010 at 22:22PM'
date=dt.datetime.strptime(date_str,'%b %d, %Y at %H:%M%p')
print(date)
# 2010-06-03 22:22:00
Or, as Muhammad Alkarouri points out, if date_strs always start with on and use a four-digit year prefixed by zero, then you could use
date_str='on Jun 03, 02010 at 22:22PM'
date=dt.datetime.strptime(date_str,'on %b %d, 0%Y at %H:%M%p')
print(date)
# 2010-06-03 22:22:00
Python's strftime and strptime use your machine's C functions of the same name. So check your local man page for what format codes are available for your machine. For a general list of format codes (which may be available) see http://au2.php.net/strftime.
A:
You are probably better of using the standard library, namely time.strptime.
In particular, the time you mentioned can be converted to a time.struct_time like so
In [9]: time.strptime("on Jun 03, 02010 at 10:22PM", "on %b %d, 0%Y at %I:%M%p")
Out[9]: time.struct_time(tm_year=2010, tm_mon=6, tm_mday=3, tm_hour=22, tm_min=22, tm_sec=0, tm_wday=3, tm_yday=154, tm_isdst=-1) #store in variable t
Now that we have the struct_time in t we can do
In [14]: time.strftime('%a, %d %b %H:%M:%S %z', t)
Out[14]: 'Thu, 03 Jun 22:22:00 '
Note that the zone information you required in "Thu, 03 Jun 22:22:00 -0000" (the -0000 bit) is not provided by the first format, therefore it won't appear in the result.
A:
I'm pretty lazy, so I'd probably use strptime and strftime:
date = strptime(dateString, 'on %b %d, %Y at %I:%M%p')
date.strftime('%a, %d %b %H:%M:%S %z')
| Convert 12hr date/time string to 24hr datetime | Like other questions asked here, im looking to do a simple conversion of time formats. I've found answers on how to do this in Perl, but not in Python.
I have a string like so:
on Jun 03, 02010 at 10:22PM
and I'd like to convert it to a datetime object like this:
Thu, 03 Jun 2010 22:22:00 -0000
I have sliced up my input like so:
date = str(comment.div.contents[5].contents)
month = date[6:9]
day = date[10:12]
year = date[15:19]
time = date[23:30]
which sets me up with some nice variables I can throw back into datetime but before I so, I must convert the time. Should I divide up time in the example above and calculate the hh and {AM|PM} separately?
| [
"Using dateutil:\nimport datetime as dt\nimport dateutil.parser as dparser\n\ndate_str='on Jun 03, 02010 at 10:22PM'\ndate=dparser.parse(date_str)\nprint(date)\n# 2010-06-03 22:22:00\nprint(date.strftime('%a, %d %b %Y %H:%M:%S'))\n# Thu, 03 Jun 2010 22:22:00\n\nIf you can somehow strip out the pesky 'on' and change... | [
4,
3,
1
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0003453702_datetime_python_time.txt |
Q:
Infinity Loop and user input as the termination
I have my code and it does go run to infinity. What I want is that if on the unix command window if the user inputs a ctrl C, I want the program to finish the current loop it in and then come out of the loop. So I want it to break, but I want it to finish the current loop. Is using ctrl C ok? Should I look to a different input?
A:
To do this correctly and exactly as you want it is a bit complicated.
Basically you want to trap the Ctrl-C, setup a flag, and continue until the start of the loop (or the end) where you check that flag. This can be done using the signal module. Fortunately, somebody has already done that and you can use the code in the example linked.
Edit: Based on your comment below, a typical usage of the class BreakHandler is:
ih = BreakHandler()
ih.enable()
for x in big_set:
complex_operation_1()
complex_operation_2()
complex_operation_3()
# Check whether there was a break.
if ih.trapped:
# Stop the loop.
break
ih.disable()
# Back to usual operation
| Infinity Loop and user input as the termination | I have my code and it does go run to infinity. What I want is that if on the unix command window if the user inputs a ctrl C, I want the program to finish the current loop it in and then come out of the loop. So I want it to break, but I want it to finish the current loop. Is using ctrl C ok? Should I look to a different input?
| [
"To do this correctly and exactly as you want it is a bit complicated.\nBasically you want to trap the Ctrl-C, setup a flag, and continue until the start of the loop (or the end) where you check that flag. This can be done using the signal module. Fortunately, somebody has already done that and you can use the code... | [
3
] | [] | [] | [
"copy_paste",
"infinity",
"loops",
"python",
"signals"
] | stackoverflow_0003453757_copy_paste_infinity_loops_python_signals.txt |
Q:
twisted: catch keyboardinterrupt and shutdown properly
UPDATE: For ease of reading, here is how to add a callback before the reactor gets shutdown:
reactor.addSystemEventTrigger('before', 'shutdown', callable)
Original question follows.
If I have a client connected to a server, and it's chilling in the reactor main loop waiting for events, when I hit CTRL-C, I get a "Connection to the other side was lost in a non-clean fashion: Connection lost." How can I set it up so that I know when a KeyboardInterrupt happens, so that I can do proper clean-up and disconnect cleanly? Or how can I implement a cleaner way to shutdown that doesn't involve CTRL-C, if possible?
A:
If you really, really want to catch C-c specifically, then you can do this in the usual way for a Python application - use signal.signal to install a handler for SIGINT that does whatever you want to do. If you invoke any Twisted APIs from the handler, make sure you use reactor.callFromThread since almost all other Twisted APIs are unsafe for invocation from signal handlers.
However, if you're really just interested in inserting some shutdown-time cleanup code, then you probably want to use IService.stopService (or the mechanism in terms of which it is implemented,reactor.addSystemEventTrigger) instead.
If you're using twistd, then using IService.stopService is easy. You already have an Application object with at least one service attached to it. You can add another one with a custom stopService method that does your shutdown work. The method is allowed to return a Deferred. If it does, then the shutdown process is paused until that Deferred fires. This lets you clean up your connections nicely, even if that involves some more network (or any other asynchronous) operations.
If you're not using twistd, then using reactor.addSystemEventTrigger directly is probably easier. You can install a before shutdown trigger which will get called in the same circumstance IService.stopService would have been called. This trigger (just any callable object) can also return a Deferred to delay shutdown. This is done with a call to reactor.addSystemEventTrigger('before', 'shutdown', callable) (sometime before shutdown is initiated, so that it's already registered whenever shutdown does happen).
service.tac gives an example of creating and using a custom service.
wxacceptance.py gives an example of using addSystemEventTrigger and delaying shutdown by (an arbitrary) three seconds.
Both of these mechanisms will give you notification whenever the reactor is stopping. This may be due to a C-c keystroke, or it may be because someone used kill -INT ..., or it may be because somewhere reactor.stop() was called. They all lead to reactor shutdown, and reactor shutdown always processes shutdown event triggers.
A:
I'm not sure whether you talking about a client or a server that you've written.
Anyway, nothing wrong with 'CTRL-C'.
If you're writing a server as an Application. Subclass from twisted.application.service.Service and define startService and stopService. Maintain a list of active protocol instances. Use stopService to go through them and close them gracefully.
If you've got a client, you could also subclass Service, but it could be simpler to use reactor.addSystemEventTrigger('before','shutdown',myCleanUpFunction), and close connection(s) gracefully in this function.
| twisted: catch keyboardinterrupt and shutdown properly | UPDATE: For ease of reading, here is how to add a callback before the reactor gets shutdown:
reactor.addSystemEventTrigger('before', 'shutdown', callable)
Original question follows.
If I have a client connected to a server, and it's chilling in the reactor main loop waiting for events, when I hit CTRL-C, I get a "Connection to the other side was lost in a non-clean fashion: Connection lost." How can I set it up so that I know when a KeyboardInterrupt happens, so that I can do proper clean-up and disconnect cleanly? Or how can I implement a cleaner way to shutdown that doesn't involve CTRL-C, if possible?
| [
"If you really, really want to catch C-c specifically, then you can do this in the usual way for a Python application - use signal.signal to install a handler for SIGINT that does whatever you want to do. If you invoke any Twisted APIs from the handler, make sure you use reactor.callFromThread since almost all oth... | [
31,
2
] | [] | [] | [
"python",
"shutdown",
"twisted"
] | stackoverflow_0003453451_python_shutdown_twisted.txt |
Q:
How to get files from directories in Python
I have a list of directories (their absolute path). Each directory contains a certain number of files. Of these files I want to get two of them from each directory. The two files I want have some string pattern in their name, for the sake of this example the strings will be 'stringA', 'stringB'.
So what I need is a list of tuples. Each tuple should have a stringA file and a stringB file in it. There should be one tuple per directory. Each directory is guaranteed to have more than 2 files and is guaranteed to have only one stringA and one stringB file.
What is the most efficient way to do this? Maybe using a list generator?
Edit:
An example:
dirs = ['/dir1', '/dir2', '/dir3']
result = [('/dir1/stringA.txt', '/dir1/stringB.txt'), ('/dir2/stringA.txt', ...) ...]
The input is directories (a list of directories) and the output should be the result (a list of tuples).
A:
See if this works for you:
import glob
result = zip(sorted(glob.glob('/dir/*stringA*')), sorted(glob.glob('/dir/*stringB*')))
| How to get files from directories in Python | I have a list of directories (their absolute path). Each directory contains a certain number of files. Of these files I want to get two of them from each directory. The two files I want have some string pattern in their name, for the sake of this example the strings will be 'stringA', 'stringB'.
So what I need is a list of tuples. Each tuple should have a stringA file and a stringB file in it. There should be one tuple per directory. Each directory is guaranteed to have more than 2 files and is guaranteed to have only one stringA and one stringB file.
What is the most efficient way to do this? Maybe using a list generator?
Edit:
An example:
dirs = ['/dir1', '/dir2', '/dir3']
result = [('/dir1/stringA.txt', '/dir1/stringB.txt'), ('/dir2/stringA.txt', ...) ...]
The input is directories (a list of directories) and the output should be the result (a list of tuples).
| [
"See if this works for you:\nimport glob\nresult = zip(sorted(glob.glob('/dir/*stringA*')), sorted(glob.glob('/dir/*stringB*')))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003454121_python.txt |
Q:
Implementing separate incrementing primary keys in Django
I am developing an internal app on the side for the company I work for, and am wanting to use Django in order to learn it and Python in general, however I've hit a bit of a snag with the PKs.
I'm trying to emulate a part of the current application where 2 MySQL tables, TaskCategory and Tasks, handle the tasks that need doing. Every Task belongs to a TaskCategory, and each item in TaskCategory has its own separate incrementing number. Thus, if "Office" has 15 tasks, adding another task to it will make its Task.taskid = 16, but adding a task to "Vehicles" will make the Tasks.taskid = 51, not 17. This then gets used as a tracking number, eg the Vehicles-51 task.
This separate incrementation was achieved by having a compound primary key in Tasks consisting of taskcategoryid and taskid (which auto-increments). Tasks.taskcategoryid is not a FK, by the way (I don't think it can be anyway, as it's part of the compound PK).
As Django doesn't like more than 1 PK column I've been having some difficulty in replicating this feature. I've tried a unique_together of taskid (auto-incrementing PK) and taskcategoryid (FK) and I've tried having 2 auto-incrementing columns (id and taskid) but you can't have more than one auto-incrementing column.
Is it possible to achieve this incrementing feature with Django? I would prefer to do it without having to hack the source code but will do it if need be.
A:
What is your goal here?
If you're trying to maintain field-to-field table compatibility with the older application, you're going to have problems because (as you've observed) Django does not do compound/composite keys -- it really prefers a surrogate key. Given the operations that Django permits, and current thinking about 'correct' database design, surrogate keys make sense.
If all you're really trying to do is keep most of the queries the same (or mostly similar), then you could leave the existing natural / composite key fields alone, but drop the old primary key constraint, add a new surrogate key for Django, and then add Meta data to your models to declare that the fields that make up the old composite keys are unique_together. Django will interpret that and add the appropriate unique indexes. You'll need to add some code to object creation to handle incrementing/assigning the TaskCategory ids, but the end result is that all of your old relationships are enforced by Django and the database.
As an example, here's part of the model from an application I put together to track players in a board game tournament:
class Player(models.Model):
badge = models.IntegerField()
name = models.CharField( max_length = 99 )
class Round(models.Model):
name = models.CharField( max_length = 9 )
number = models.IntegerField()
class Table(models.Model):
round = models.ForeignKey( Round )
number = models.IntegerField( 'table number')
class Meta:
unique_together = ( 'round', 'number' )
class Seat(models.Model):
table = models.ForeignKey( Table )
position = models.IntegerField( 'seat number' )
player = models.ForeignKey( Player )
class Meta:
unique_together = ( 'table', 'seat' )
In this case, I'm using unique_together to ensure that while table numbers are reused for different rounds, and that seat positions are the same across tables, you will never encounter the same combination of round, table, and seat more than once.
| Implementing separate incrementing primary keys in Django | I am developing an internal app on the side for the company I work for, and am wanting to use Django in order to learn it and Python in general, however I've hit a bit of a snag with the PKs.
I'm trying to emulate a part of the current application where 2 MySQL tables, TaskCategory and Tasks, handle the tasks that need doing. Every Task belongs to a TaskCategory, and each item in TaskCategory has its own separate incrementing number. Thus, if "Office" has 15 tasks, adding another task to it will make its Task.taskid = 16, but adding a task to "Vehicles" will make the Tasks.taskid = 51, not 17. This then gets used as a tracking number, eg the Vehicles-51 task.
This separate incrementation was achieved by having a compound primary key in Tasks consisting of taskcategoryid and taskid (which auto-increments). Tasks.taskcategoryid is not a FK, by the way (I don't think it can be anyway, as it's part of the compound PK).
As Django doesn't like more than 1 PK column I've been having some difficulty in replicating this feature. I've tried a unique_together of taskid (auto-incrementing PK) and taskcategoryid (FK) and I've tried having 2 auto-incrementing columns (id and taskid) but you can't have more than one auto-incrementing column.
Is it possible to achieve this incrementing feature with Django? I would prefer to do it without having to hack the source code but will do it if need be.
| [
"What is your goal here?\nIf you're trying to maintain field-to-field table compatibility with the older application, you're going to have problems because (as you've observed) Django does not do compound/composite keys -- it really prefers a surrogate key. Given the operations that Django permits, and current thi... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003453897_django_python.txt |
Q:
How to get two python processes talking over pipes?
I'm having troubles getting this to work. Basically I have a python program that expect some data in stdin, that is reading it as sys.stdin.readlines() I have tested this and it is working without problems with things like echo "" | myprogram.py
I have a second program that using the subprocess module calls on the first program with the following code
proc = subprocess.Popen(final_shell_cmd,
stderr=subprocess.PIPE, stdout=subprocess.PIPE,
shell=False), env=shell_env)
f = ' '.join(shell_cmd_args)
#f.append('\4')
return proc.communicate(f)
The second program is a daemon and i have discovered that the second program works well as long as I hit ctrl-d after calling it from the first program.
So it seems there is something wrong with subprocess not closing the file and my first program expecting more input when nothing more should be sending.
anyone has any idea how I can get this working?
The main problem here is that "shell_cmd_args" may contain passwords and other sensitive information that we do not want to pass in as the command name as it will show in tools like "ps".
A:
You want to redirect the subprocess's stdin, so you need stdin=subprocess.PIPE.
You should not need to write Control-D ('\4') to the file object. Control-D tells the shell to close the standard input that's connected to the program. The program doesn't see a Control-D character in that context.
| How to get two python processes talking over pipes? | I'm having troubles getting this to work. Basically I have a python program that expect some data in stdin, that is reading it as sys.stdin.readlines() I have tested this and it is working without problems with things like echo "" | myprogram.py
I have a second program that using the subprocess module calls on the first program with the following code
proc = subprocess.Popen(final_shell_cmd,
stderr=subprocess.PIPE, stdout=subprocess.PIPE,
shell=False), env=shell_env)
f = ' '.join(shell_cmd_args)
#f.append('\4')
return proc.communicate(f)
The second program is a daemon and i have discovered that the second program works well as long as I hit ctrl-d after calling it from the first program.
So it seems there is something wrong with subprocess not closing the file and my first program expecting more input when nothing more should be sending.
anyone has any idea how I can get this working?
The main problem here is that "shell_cmd_args" may contain passwords and other sensitive information that we do not want to pass in as the command name as it will show in tools like "ps".
| [
"You want to redirect the subprocess's stdin, so you need stdin=subprocess.PIPE.\nYou should not need to write Control-D ('\\4') to the file object. Control-D tells the shell to close the standard input that's connected to the program. The program doesn't see a Control-D character in that context.\n"
] | [
2
] | [] | [] | [
"python",
"shell",
"subprocess"
] | stackoverflow_0003454427_python_shell_subprocess.txt |
Q:
Is there a way to format a variety of currencies on Python?
I've got a Python web server (mod_python, if that makes any difference) that I want to start formatting some currency. I've got two pieces of information when I format the currency - the value (as a number) and the currency (as the three-letter ISO 4217 code). I can also retrieve the country (or even city) that the currency is being formatted in. I can expect a large variety of currencies to be formatted - USD, CAD, JPY, GBP, EUR, etc. Each request might be in a different currency.
I'm aware of the locale module, but it doesn't do what I want. That module seems to be based around the computer's locale, so it doesn't work well for formatting any given currency.
Is there a way to do this in Python? Or does anyone know of a good library that can solve this problem?
A:
For my internationalization needs, I almost invariably turn to ICU, a truly awesome package in both breadth and depth -- usually via pyIcu, although in the past I've had to do some wrapping of my own when pyIcu hadn't yet wrapped some corner of ICU I needed (I'm not sure if they're currently wrapping all the currency-formatting operations you require).
The docs for PyIcu are here, to be read "on top of" ICU's own docs here -- in other words, the PyIcu-specific document is essentially a "phrasebook and dictionary" on how to "translate" ICU's own, C++ focused docs, into docs for PyIcu (and Python-focused ones;-). Yeah, I know, not ideal -- not the only open-source package with imperfect docs I guess (me, I think that's an opportunity for some enterprising soul to write a "PyIcu, the missing manual" book, or the like;-).
A:
I'm sure you could use regex or decimal formatting, but this module seems promising:
http://code.google.com/p/python-money/
Python-money provides carefully
designed basic Python primitives for
working with money and currencies.
The primary objectives of this module
is to aid in the development of
financial applications by increasing
testability and reusability, reducing
code duplication and reducing the risk
of defects occurring in the code.
The module defines two basic Python
classes -- a Currency class and a
Money class. It also pre-defines all
the world's currencies, according to
the ISO 4217 standard. The classes
define some basic operations for
working with money, overriding
Python's addition, substraction,
multiplication, etc. in order to
account for working with money in
different currencies. They also define
currency-aware comparison operators.
To avoid floating point precision
errors in monetary calculations, the
module uses Python's Decimal type
exclusively.
The design of the module is based on
the Money enterprise design pattern,
as described in Martin Fowler's
"Patterns of Enterprise Application
Architecture".
| Is there a way to format a variety of currencies on Python? | I've got a Python web server (mod_python, if that makes any difference) that I want to start formatting some currency. I've got two pieces of information when I format the currency - the value (as a number) and the currency (as the three-letter ISO 4217 code). I can also retrieve the country (or even city) that the currency is being formatted in. I can expect a large variety of currencies to be formatted - USD, CAD, JPY, GBP, EUR, etc. Each request might be in a different currency.
I'm aware of the locale module, but it doesn't do what I want. That module seems to be based around the computer's locale, so it doesn't work well for formatting any given currency.
Is there a way to do this in Python? Or does anyone know of a good library that can solve this problem?
| [
"For my internationalization needs, I almost invariably turn to ICU, a truly awesome package in both breadth and depth -- usually via pyIcu, although in the past I've had to do some wrapping of my own when pyIcu hadn't yet wrapped some corner of ICU I needed (I'm not sure if they're currently wrapping all the curre... | [
2,
1
] | [] | [] | [
"currency",
"formatting",
"python"
] | stackoverflow_0003454074_currency_formatting_python.txt |
Q:
How to efficiently parse emails without touching attachments using Python
I'm playing with Python imaplib (Python 2.6) to fetch emails from GMail. Everything I fetch an email with method http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch I get whole email. I need only text part and also parse names of attachments, without downloading them. How this can be done? I see that emails returned by GMail follow the same format that browsers send to HTTP servers.
A:
Take a look at this recipe: http://code.activestate.com/recipes/498189/
I adapted it slightly to print the From, Subject, Date, name of attachments, and message body (just plaintext for now -- its trivial to add html messages).
I used the Gmail pop3 server in this case, but it should work for IMAP as well.
import poplib, email, string
mailserver = poplib.POP3_SSL('pop.gmail.com')
mailserver.user('recent:YOURUSERNAME') #use 'recent mode'
mailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!
numMessages = len(mailserver.list()[1])
for i in reversed(range(numMessages)):
message = ""
msg = mailserver.retr(i+1)
str = string.join(msg[1], "\n")
mail = email.message_from_string(str)
message += "From: " + mail["From"] + "\n"
message += "Subject: " + mail["Subject"] + "\n"
message += "Date: " + mail["Date"] + "\n"
for part in mail.walk():
if part.is_multipart():
continue
if part.get_content_type() == 'text/plain':
body = "\n" + part.get_payload() + "\n"
dtypes = part.get_params(None, 'Content-Disposition')
if not dtypes:
if part.get_content_type() == 'text/plain':
continue
ctypes = part.get_params()
if not ctypes:
continue
for key,val in ctypes:
if key.lower() == 'name':
message += "Attachment:" + val + "\n"
break
else:
continue
else:
attachment,filename = None,None
for key,val in dtypes:
key = key.lower()
if key == 'filename':
filename = val
if key == 'attachment':
attachment = 1
if not attachment:
continue
message += "Attachment:" + filename + "\n"
if body:
message += body + "\n"
print message
print
This should be enough to get you heading in the right direction.
A:
You can get only the plain text of the email by doing something like:
connection.fetch(id, '(BODY[1])')
For the gmail messages I've seen, section 1 has the plaintext, including multipart junk. This may not be so robust.
I don't know how to get the name of the attachment without all of it. I haven't tried using partials.
A:
I'm afraid you're out of luck. According to this post, there are only two parts to the email - the header and the body. The body is where the attachments are if there are any and you have to download the whole body before extracting only the message text. The info about the FETCH command found here also supports this opinion. While it says you can extract partials of the body, these are specified in terms of octets which doesn't really help.
| How to efficiently parse emails without touching attachments using Python | I'm playing with Python imaplib (Python 2.6) to fetch emails from GMail. Everything I fetch an email with method http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch I get whole email. I need only text part and also parse names of attachments, without downloading them. How this can be done? I see that emails returned by GMail follow the same format that browsers send to HTTP servers.
| [
"Take a look at this recipe: http://code.activestate.com/recipes/498189/\nI adapted it slightly to print the From, Subject, Date, name of attachments, and message body (just plaintext for now -- its trivial to add html messages).\nI used the Gmail pop3 server in this case, but it should work for IMAP as well.\nimpo... | [
5,
2,
0
] | [] | [] | [
"gmail",
"imap",
"imaplib",
"parsing",
"python"
] | stackoverflow_0002301213_gmail_imap_imaplib_parsing_python.txt |
Q:
How does Python stack up to other scripting languages?
I'm learning Python (and it's my first programming language so don't be too intense with your reasons) and I wanted to know how it stacks up to other scripting languages, like Perl and Ruby. What is Python better in comparison to other scripting languages, and what is it worse for?
A:
First off, an advice - look for POSITIVE things said from opposite sides. Meaning, you should trust positive things said about Perl by Python-related sources (or positive things said about Python by Perl related sources) much more than the opposite.
The two reasons are that:
1) People who have reason to like Python would NOT be inclined to say good things about Perl unless they were truly trying to be objective (which is what you ideally want). And vice versa - it's a problem with human biases and motivations, NOT with either Perl or Python.
2) People writing such comparisons favoring one language are VERY often completely mis-informed and not very practiced about the one they are unfavorable about. As evidence see this article: http://python.about.com/od/gettingstarted/ss/whatispython_5.htm - pretty much anything it has to say about Perl is, to put it gently and mildly, a comlpete and utter bunk. I'm sure there are equally moronic Python put-downs from Perl fans, I just never read enough about Python to be able to think one up off the top of my head.
Second, please be aware that, at least for Perl - and I strongly suspect, for Ruby and Python - the moniker of "scripting" language is not really applicable anymore.
Yes, their (especially Perl's) origins are somewhat connected to shell scripting, and yes, a small subset of the languages capabilities can be - and are - used to write shell scripts, and make that small task very easy and extremely productive.
However, at this point in its long history, Perl is in no way even remotely restricted to those capabilities, and is used for developing anything from scripts to web frameworks to servers to large scale enterprise software to bio-informatics software.
Third, please look at this - it has a lot of links:
http://wiki.python.org/moin/LanguageComparisons
A:
I'm learning Python (and it's my first programming language so don't be too intense with your reasons) and I wanted to know how it stacks up to other scripting languages, like Perl and Ruby. What is Python better in comparison to other scripting languages, and what is it worse for?
IMO.
I have tried Python 2.x for some time and went back to the Perl and C++.
What is good about Python. Python features better portability and has modern GUI libraries. Standard library in some places is also very very nice (I esp. liked random). Execution speed of arithmetic expressions beats that of Perl.
What is bad about Python. Poor documentation. No warnings, no typing whatsoever combined with weak typing/language's dynamic nature is a hell. Learning easy - using hard, mainly due to immature optimizer driving the need to think about performance edge cases quite early in the development cycle. (That some times reminded me of the Pascal.) OO is a mess at the moment: distinct features and differences between old-style and new-style classes are not spelled out very well; libraries do not mention what type of classes they do define.
Poor documentation probably should be highlighted. There are piles of standard functions but their purpose in life isn't really specified nor decent examples are given. And better half of those standard functions in Perl land would have been sitting somewhere in the perldoc perlguts. Anyhow, looking up stuff is much faster with Google.
Lack of warnings and lack of typing (and that compared to the weak Perl's use warnings/use strict and sub prototypes) is what in the end drove me back. Partially it is because that I write code faster than I can read it thus I like to rely on the compiler/interpreter to tell me where I might have wrote something I haven't really meant.
Also excuse me, but I would throw that at Python again: using indentation to denote code structure is kind'a kinky. I do not mind it per se and for short functions it is very nice. But after one week I have found that I do read Python code slower (compared to C++ or Perl) in greater part because I have to always extra check whether the statement really closed or it still goes on. If code doesn't fit one screen, it becomes a chore to always press PgDown/PgUp just to check. Never before I were that appreciative of the {}s.
All considered, Python is at the moment a mess. Worthy contender I do keep an eye on, but not mature enough for my daily needs. If I were making decision about learning Python now, I would have instead waited for Python 3.x to mature. Many things one would learn now with Python 2.x might be useless in Python 3.x. And Python 3.x is at the moment isn't very useful since many libraries were not yet ported to it.
P.S. Most bogus part I have encountered is the function pointers. I have discovered them sooner than I needed them by writing start_time = time.time and time_elapsed = time.time() - start_time. Half hour later when script finished instead of results I was presented with nice interpreter exception telling me that I cannot subtract function object. And the half hour was due to the standard for loop, as tutorials have taught me. Optimizations I have looked up later (range vs. xrange, manual loop unrolling) made the script run in less than one minute.
A:
Here is a nice overview of why Python (the language) is a very nice place to start programming: http://www.python.org/about/
Python includes a very comprehensive standard library (i.e. "batteries included") which allows you to solve many programming problems.
Once you've learned Python, I'd suggest you also learn other languages such as Ruby, because different languages provide different paradigms for thinking about programming, thus expanding your knowledge of models of computation.
| How does Python stack up to other scripting languages? | I'm learning Python (and it's my first programming language so don't be too intense with your reasons) and I wanted to know how it stacks up to other scripting languages, like Perl and Ruby. What is Python better in comparison to other scripting languages, and what is it worse for?
| [
"First off, an advice - look for POSITIVE things said from opposite sides. Meaning, you should trust positive things said about Perl by Python-related sources (or positive things said about Python by Perl related sources) much more than the opposite. \nThe two reasons are that:\n1) People who have reason to like Py... | [
10,
6,
2
] | [] | [] | [
"comparison",
"perl",
"python",
"ruby"
] | stackoverflow_0003452729_comparison_perl_python_ruby.txt |
Q:
conditionally setting and conditionally using a variable python
I know it is bad convention/design to conditionally declare a variable. i.e.:
if some_boolean:
x = 1
where x is not declared anywhere else. But is it bad to conditionally declare a variable if you only use it later on if that condition is met?
if some_boolean and some_other_boolean:
x+=1
A:
It's dubious style, as it's prone to bugs based on imperfect, impartial understanding on some future maintainer's part. I also think that initially setting variables to None (unless more useful values are known for them) is helpful to readability, in part because it gives you one, natural place to document all of the variables with comments (rather than spreading such comments all over the place, which makes them hard to find;-).
A:
if your code look like this
if some_boolean:
x = 1
# some actions
# not changing some_boolean
# but calculating some_other_boolean
# ...
if some_boolean and some_other_boolean:
x+=1
Can it be refactored to
def some_actions(some_args,...):
#...
def calculate_some_other_boolean(some_other_args,...):
#...
if some_boolean:
x = 1
some_actions(some_args,...)
if calculate_some_other_boolean(some_other_args,...):
x+=1
else:
some_actions(some_args,...)
?
A:
From a very simple design perspective, I'd just default the boolean to false even if it maybe won't be used later. That way the boolean in question is not maybe defined or maybe actually a boolean value, and in the event that it is used, it has a proper value.
If you have two or three booleans set to false and they never get used, it's not going to make any significant difference in a big picture sense. If you have more than a few, though, it may indicate a design problem.
| conditionally setting and conditionally using a variable python | I know it is bad convention/design to conditionally declare a variable. i.e.:
if some_boolean:
x = 1
where x is not declared anywhere else. But is it bad to conditionally declare a variable if you only use it later on if that condition is met?
if some_boolean and some_other_boolean:
x+=1
| [
"It's dubious style, as it's prone to bugs based on imperfect, impartial understanding on some future maintainer's part. I also think that initially setting variables to None (unless more useful values are known for them) is helpful to readability, in part because it gives you one, natural place to document all of... | [
2,
1,
0
] | [] | [] | [
"convention",
"python"
] | stackoverflow_0003454501_convention_python.txt |
Q:
Django: automatically import MEDIA_URL in context
like exposed here, one can set a MEDIA_URL in settings.py (for example i'm pointing to Amazon S3) and serve the files in the view via {{ MEDIA_URL }}. Since MEDIA_URL is not automatically in the context, one have to manually add it to the context, so, for example, the following works:
#views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def test(request):
return render_to_response('test.html', {}, context_instance=RequestContext(request))
This means that in each view.py file i have to add from django.template import RequestContext and in each response i have to explicitly specify context_instance=RequestContext(request).
Is there a way to automatically (DRY) add MEDIA_URL to the default context? Thanks in advance.
A:
There is a generic view for this use :
direct_to_template(request, template, extra_context=None, mimetype=None, **kwargs)
It is not well documented (in my opinion : it doesn't tell that it uses a RequestContext), so I advise you to check out the implementation :
http://code.djangoproject.com/browser/django/trunk/django/views/generic/simple.py
I think it is what you are looking for ...
A:
Add "django.core.context_processors.media" to your TEMPLATE_CONTEXT_PROCESSORS in the settings file.
| Django: automatically import MEDIA_URL in context | like exposed here, one can set a MEDIA_URL in settings.py (for example i'm pointing to Amazon S3) and serve the files in the view via {{ MEDIA_URL }}. Since MEDIA_URL is not automatically in the context, one have to manually add it to the context, so, for example, the following works:
#views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def test(request):
return render_to_response('test.html', {}, context_instance=RequestContext(request))
This means that in each view.py file i have to add from django.template import RequestContext and in each response i have to explicitly specify context_instance=RequestContext(request).
Is there a way to automatically (DRY) add MEDIA_URL to the default context? Thanks in advance.
| [
"There is a generic view for this use :\ndirect_to_template(request, template, extra_context=None, mimetype=None, **kwargs)\n\nIt is not well documented (in my opinion : it doesn't tell that it uses a RequestContext), so I advise you to check out the implementation :\nhttp://code.djangoproject.com/browser/django/tr... | [
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002880748_django_python.txt |
Q:
How to save a whole web page with something block in it
I want to save a web page. I use python urllib to parse the web page. But I
find the saved file, where some content is missing. The missing part
is block from the source web page, such as this part <div
style="display: block;" id="GeneInts">...</div>.
I don't know how to parse a whole page without something block in it. Could you help me
figure it out? Thank you!
This is my program
url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp?Param=4502931&ProtId=1&ProtType=Receptor'
f = urllib.urlretrieve(url,'test.html')
A:
Whenever I need to let Javascript operate on a page before I can scrape it, the first thing I always turn to is SeleniumRC -- while it's mainly designed for purposes of testing, I've never found a better tool for this challenging task. For the "using it from Python" part, see here and links therefrom.
A:
That page generates a great deal of its content with JavaScript executed at load-time, including, I think, the part you're trying to extract. You need a screen-scraper that can run JavaScript and then save out the modified DOM. I don't know where you get one of those.
| How to save a whole web page with something block in it | I want to save a web page. I use python urllib to parse the web page. But I
find the saved file, where some content is missing. The missing part
is block from the source web page, such as this part <div
style="display: block;" id="GeneInts">...</div>.
I don't know how to parse a whole page without something block in it. Could you help me
figure it out? Thank you!
This is my program
url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp?Param=4502931&ProtId=1&ProtType=Receptor'
f = urllib.urlretrieve(url,'test.html')
| [
"Whenever I need to let Javascript operate on a page before I can scrape it, the first thing I always turn to is SeleniumRC -- while it's mainly designed for purposes of testing, I've never found a better tool for this challenging task. For the \"using it from Python\" part, see here and links therefrom.\n",
"Th... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0003454819_python.txt |
Q:
Wikipedia with Python
I have this very simple python code to read xml for the wikipedia api:
import urllib
from xml.dom import minidom
usock = urllib.urlopen("http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500")
xmldoc=minidom.parse(usock)
usock.close()
print xmldoc.toxml()
But this code returns with these errors:
Traceback (most recent call last):
File "/home/user/workspace/wikipediafoundations/src/list.py", line 5, in <module><br>
xmldoc=minidom.parse(usock)<br>
File "/usr/lib/python2.6/xml/dom/minidom.py", line 1918, in parse<br>
return expatbuilder.parse(file)<br>
File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 928, in parse<br>
result = builder.parseFile(file)<br>
File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 207, in parseFile<br>
parser.Parse(buffer, 0)<br>
xml.parsers.expat.ExpatError: syntax error: line 1, column 62<br>
I have no clue as I just learning python. Is there a way to get an error with more detail? Does anyone know the solution? Also, please recommend a better language to do this in.
Thank You,
Venkat Rao
A:
The URL you're requesting is an HTML representation of the XML that would be returned:
http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500
So the XML parser fails. You can see this by pasting the above in a browser. Try adding a format=xml at the end:
http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500&format=xml
as documented on the linked page:
http://en.wikipedia.org/w/api.php
| Wikipedia with Python | I have this very simple python code to read xml for the wikipedia api:
import urllib
from xml.dom import minidom
usock = urllib.urlopen("http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500")
xmldoc=minidom.parse(usock)
usock.close()
print xmldoc.toxml()
But this code returns with these errors:
Traceback (most recent call last):
File "/home/user/workspace/wikipediafoundations/src/list.py", line 5, in <module><br>
xmldoc=minidom.parse(usock)<br>
File "/usr/lib/python2.6/xml/dom/minidom.py", line 1918, in parse<br>
return expatbuilder.parse(file)<br>
File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 928, in parse<br>
result = builder.parseFile(file)<br>
File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 207, in parseFile<br>
parser.Parse(buffer, 0)<br>
xml.parsers.expat.ExpatError: syntax error: line 1, column 62<br>
I have no clue as I just learning python. Is there a way to get an error with more detail? Does anyone know the solution? Also, please recommend a better language to do this in.
Thank You,
Venkat Rao
| [
"The URL you're requesting is an HTML representation of the XML that would be returned:\nhttp://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500\n\nSo the XML parser fails. You can see this by pasting the above in a browser. Try adding a format=xml at the end:\nhttp://en.wikipedia.org... | [
9
] | [] | [] | [
"python",
"wikipedia",
"xml"
] | stackoverflow_0003455104_python_wikipedia_xml.txt |
Q:
I extend QApplication and calling a method after exec_ does not work
The following code works (and it's very simple):
class Scrape(QApplication):
def __init__(self):
super(Scrape, self).__init__(None)
self.webView = QWebView()
self.webView.loadFinished.connect(self.loadFinished)
def load(self, url):
self.webView.load(QUrl(url))
def loadFinished(self):
documentElement = self.webView.page().currentFrame().documentElement()
myScrape = Scrape()
myScrape.load('http://google.com/ncr')
myScrape.exec_()
but I do not really understand why the exec_() needs to be the last call and if it needs to be then what that load() really does...? How would any of this would work if I would need to load, say, two web pages?
A:
The exec_ call starts the event loop. This is where keyboard and mouse events, timer events, as well as async slot calls are dispatched.
The load method does what you expect: sets the Url in the view. This doesn't need events to be processed for it to work. But if you don't finish with exec_, there will be nothing to deal with events, or to prevent the program from just finishing up and exiting.
The exec_ method, as the term 'event loop' indicates, loops until the application quits. Functions called after that won't be called until the event loop exits.
If you want to 'do things' in your program, normally you would work within the event-driven framework. To load pages, you might hook up a button that will fire an event, which is connected to a function that loads a different page. Or, you might set up a timer that calls a function that sets the Url from a list.
An example of connecting signals and slots (from here):
# Define a new signal called 'trigger' that has no arguments.
trigger = QtCore.pyqtSignal()
def connect_and_emit_trigger(self):
# Connect the trigger signal to a slot.
self.trigger.connect(self.handle_trigger)
# Emit the signal.
self.trigger.emit()
def handle_trigger(self):
# Show that the slot has been called.
print "trigger signal received"
| I extend QApplication and calling a method after exec_ does not work | The following code works (and it's very simple):
class Scrape(QApplication):
def __init__(self):
super(Scrape, self).__init__(None)
self.webView = QWebView()
self.webView.loadFinished.connect(self.loadFinished)
def load(self, url):
self.webView.load(QUrl(url))
def loadFinished(self):
documentElement = self.webView.page().currentFrame().documentElement()
myScrape = Scrape()
myScrape.load('http://google.com/ncr')
myScrape.exec_()
but I do not really understand why the exec_() needs to be the last call and if it needs to be then what that load() really does...? How would any of this would work if I would need to load, say, two web pages?
| [
"The exec_ call starts the event loop. This is where keyboard and mouse events, timer events, as well as async slot calls are dispatched.\nThe load method does what you expect: sets the Url in the view. This doesn't need events to be processed for it to work. But if you don't finish with exec_, there will be nothin... | [
2
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0003455260_pyqt4_python.txt |
Q:
Python: Simple file formating problem
I'm using the code below to to write to a file but at the moment it writes everything onto a new line.
import csv
antigens = csv.reader(open('PAD_n1372.csv'), delimiter=',')
lista = []
pad_file = open('pad.txt','w')
for i in antigens:
lista.append(i[16])
lista.append(i[21])
lista.append(i[0])
for k in lista:
pad_file.write(k+',')
pad_file.write('\n')
If say my "lista" looks like
[['apple','car','red'],['orange','boat','black']]
I would like the output in my text file to be:
apple,car,red
orange,boat,black
I know my new line character is in the wrong place but I do now know where to place it, also how would I remove the comma from the end of each line?
EDIT
Sorry my "lista" looks like
['apple','car','red','orange','boat','black']
A:
If lista is [['apple','car','red'],['orange','boat','black']], then each k in your loop is going to be one of the sub-lists, so all you need to do is join the elements of that sub-list on a , and output that as a single line:
for k in lista:
pad_file.write(','.join(k))
pad_file.write('\n')
Edit based on comments: If lista is ['apple, 'car', 'red', 'orange', 'boat', 'black'] and you want 3 elements per line, you can just change the for target to a list comprehension that returns the appropriate sub-lists:
for k in [lista[x:x+3] for x in xrange(0, len(lista), 3)]:
pad_file.write(','.join(k))
pad_file.write('\n')
There are other ways to break a list into chunks; see this SO question
A:
It looks like you are processing an input csv file with 22+ columns. Why not just use csv.writer as well to rewrite each line?
A short, working example:
import csv
# generate an input file
f = open('in.csv','w')
f.write('''\
Col1,Col2,Col3,Col4,Col5
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
''')
f.close()
# open the files (csv likes binary mode)
input = open('in.csv','rb')
output = open('out.csv','wb')
antigens = csv.reader(input)
pad_file = csv.writer(output)
for i in antigens:
pad_file.writerow([i[4],i[2],i[0]])
input.close()
output.close()
"out.csv" contains:
Col5,Col3,Col1
5,3,1
10,8,6
15,13,11
| Python: Simple file formating problem | I'm using the code below to to write to a file but at the moment it writes everything onto a new line.
import csv
antigens = csv.reader(open('PAD_n1372.csv'), delimiter=',')
lista = []
pad_file = open('pad.txt','w')
for i in antigens:
lista.append(i[16])
lista.append(i[21])
lista.append(i[0])
for k in lista:
pad_file.write(k+',')
pad_file.write('\n')
If say my "lista" looks like
[['apple','car','red'],['orange','boat','black']]
I would like the output in my text file to be:
apple,car,red
orange,boat,black
I know my new line character is in the wrong place but I do now know where to place it, also how would I remove the comma from the end of each line?
EDIT
Sorry my "lista" looks like
['apple','car','red','orange','boat','black']
| [
"If lista is [['apple','car','red'],['orange','boat','black']], then each k in your loop is going to be one of the sub-lists, so all you need to do is join the elements of that sub-list on a , and output that as a single line:\nfor k in lista:\n pad_file.write(','.join(k))\n pad_file.write('\\n')\n\n\nEdit ba... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003452320_python.txt |
Q:
Passing instance/default value to a ModelFormSet for the empty forms to use, in a view
How do i pre-populate the exclude fields in a ModelFormSet. AuthorFormSet below doesn't take an instance argument here, only queryset. So how do i force the empty forms coming in not to have a NULL/None user attribute. I want to be able to set that user field to request.user
models.py
class Author(models.Model):
user = models.ForeignKey(User, related_name='author')
# assume some other fields here, but not relevant to the discussion.
forms.py
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
class BaseAuthorFormSet(BaseModelFormSet):
"""will do some clean() here"""
pass
AuthorFormSet = modelformset_factory(Author,\
form=AuthorForm, \
formset=BaseAuthorFormSet, extra=1,\
exclude=('user',)
)
views.py
def my_view(request):
if request.method == 'POST':
formset = AuthorFormSet(request.POST)
if form.is_valid():
form.save() # This will cause problems
# for the empty form i added,
# since user can't be null.
EDIT
This is what i ended up doing in my view. Wogan's answer is partly correct, i think it's just missing the iterating over all the forms part.
for form in formset.forms:
form.instance.user = request.user
formset.save()
A:
You can exclude fields in the model form, these will then be excluded from the formset created by modelformset_factory.
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
exclude = ('user',)
In your view, pass commit=False to the form's save() method, then set the user field manually:
def my_view(request):
if request.method == 'POST':
formset = AuthorFormSet(request.POST)
if formset.is_valid():
for author in formset.save(commit=False):
author.user = request.user
author.save()
formset.save_m2m() # if your model has many to many relationships you need to call this
| Passing instance/default value to a ModelFormSet for the empty forms to use, in a view | How do i pre-populate the exclude fields in a ModelFormSet. AuthorFormSet below doesn't take an instance argument here, only queryset. So how do i force the empty forms coming in not to have a NULL/None user attribute. I want to be able to set that user field to request.user
models.py
class Author(models.Model):
user = models.ForeignKey(User, related_name='author')
# assume some other fields here, but not relevant to the discussion.
forms.py
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
class BaseAuthorFormSet(BaseModelFormSet):
"""will do some clean() here"""
pass
AuthorFormSet = modelformset_factory(Author,\
form=AuthorForm, \
formset=BaseAuthorFormSet, extra=1,\
exclude=('user',)
)
views.py
def my_view(request):
if request.method == 'POST':
formset = AuthorFormSet(request.POST)
if form.is_valid():
form.save() # This will cause problems
# for the empty form i added,
# since user can't be null.
EDIT
This is what i ended up doing in my view. Wogan's answer is partly correct, i think it's just missing the iterating over all the forms part.
for form in formset.forms:
form.instance.user = request.user
formset.save()
| [
"You can exclude fields in the model form, these will then be excluded from the formset created by modelformset_factory.\nclass AuthorForm(forms.ModelForm):\n class Meta:\n model = Author\n exclude = ('user',)\n\nIn your view, pass commit=False to the form's save() method, then set the user field m... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003453416_django_django_forms_python.txt |
Q:
Calling code in a string without exec/eval, python
I have this code that executes when a player attempts to eat something:
def eat(target='object'):
global current_room
global locations
global inventory
if target in inventory:
items[target]['on_eat'] #This is showing no results.
else:
print 'You have no ' + target + ' to eat.'
and this code for items(trimmed)
items = {
'strawberry': {
'weight': 1,
'text': 'The strawberry is red',
'on_eat': "normal_eat('strawberry', 'pretty good, but not as sweet as you expected')"
},
'trees': {
'weight': 50,
'text': 'The trees are tall with large, leaf filled branches blocking out a majority of sunlight.',
'on_eat': "forcesay('Eating trees? What the hell is your problem?')"
}
}
Is there a valid way of calling items[whatever]['on_eat'] without doing something silly like exec() or eval()? If not, alternative formatting as an example would also be appreciated.
Before this the items[everyitems]['on_eat'] values were not strings, but that executed the on_eat for every item as soon as the code was ran.
I have seen many answers to similar questions, but they don't deal with arguments for functions unique- to better put that, they were more like this
A:
You can store your function and function arguments as a partial:
from functools import partial
items = {
'strawberry': {
'weight': 1,
'text': 'The strawberry is red',
'on_eat': partial(normal_eat, 'strawberry', 'pretty good, but not as sweet as you expected')
},
'trees': {
'weight': 50,
'text': 'The trees are tall with large, leaf filled branches blocking out a majority of sunlight.',
'on_eat': partial(forcesay, 'Eating trees? What the hell is your problem?')
}
def eat(target='object'):
# those globals are probably not necessary
if target in inventory:
items[target]['on_eat']() #Add ()'s to call the partial
else:
print 'You have no ' + target + ' to eat.'
A:
you can use the code module
def eat(target='object'):
import code
console = code.InteractiveConsole(locals()) # make a python interpreter with local vars
if target in inventory:
console.push("items[target]['on_eat']")
else:
print 'You have no ' + target + ' to eat.'
A:
An alternative to partial functions is to write items like this
items = {
'strawberry': {
'weight': 1,
'text': 'The strawberry is red',
'on_eat': (normal_eat,('strawberry', 'pretty good, but not as sweet as you expected'))
},
'trees': {
'weight': 50,
'text': 'The trees are tall with large, leaf filled branches blocking out a majority of sunlight.',
'on_eat': (forcesay,('Eating trees? What the hell is your problem?',))
}
}
and call it like this
def eat(target='object'):
if target in inventory:
func, args = items[target]['on_eat']
func(*args)
else:
print 'You have no ' + target + ' to eat.'
You don't need those global statements there unless you will be reassigning them
| Calling code in a string without exec/eval, python | I have this code that executes when a player attempts to eat something:
def eat(target='object'):
global current_room
global locations
global inventory
if target in inventory:
items[target]['on_eat'] #This is showing no results.
else:
print 'You have no ' + target + ' to eat.'
and this code for items(trimmed)
items = {
'strawberry': {
'weight': 1,
'text': 'The strawberry is red',
'on_eat': "normal_eat('strawberry', 'pretty good, but not as sweet as you expected')"
},
'trees': {
'weight': 50,
'text': 'The trees are tall with large, leaf filled branches blocking out a majority of sunlight.',
'on_eat': "forcesay('Eating trees? What the hell is your problem?')"
}
}
Is there a valid way of calling items[whatever]['on_eat'] without doing something silly like exec() or eval()? If not, alternative formatting as an example would also be appreciated.
Before this the items[everyitems]['on_eat'] values were not strings, but that executed the on_eat for every item as soon as the code was ran.
I have seen many answers to similar questions, but they don't deal with arguments for functions unique- to better put that, they were more like this
| [
"You can store your function and function arguments as a partial:\nfrom functools import partial\n\nitems = { \n'strawberry': { \n 'weight': 1, \n 'text': 'The strawberry is red', \n 'on_eat': partial(normal_eat, 'strawberry', 'pretty good, but not as sweet as you expected') \n }, \n'trees': { \n 'we... | [
6,
1,
0
] | [] | [] | [
"eval",
"exec",
"python",
"reference"
] | stackoverflow_0003455490_eval_exec_python_reference.txt |
Q:
Can selenium open a search result page?
I'm new to selenium. I want to ask about if there's a easy way to open a search result page of some urls, not just the homepages.
for examples,
I search stack overflow in google. The url is here, but the return page is google homepage.Is it possible to get the result page directly? I want to scratch some result pages. If I just open the homepage then input the keywords to get the result pages, I think this way should be very slow.
Thank you for your answers.
from selenium import selenium
url ='http://www.google.com/search?hl=en&source=hp&q=stack+overflow&aq=o&aqi=&aql=&oq=&gs_rfai='
sel = selenium('localhost', 4444, '*firefox', url)
sel.start()
sel.open('/')
sel.wait_for_page_to_load(10000)
A:
You should change your code:
from selenium import selenium
url ='http://www.google.com/'
sel = selenium('localhost', 4444, '*firefox', url)
sel.start()
sel.open('/search?hl=en&source=hp&q=stack+overflow&aq=o&aqi=&aql=&oq=&gs_rfai=')
sel.wait_for_page_to_load(10000)
So your url is pointing to the start page and you do open what you need - the search result
| Can selenium open a search result page? | I'm new to selenium. I want to ask about if there's a easy way to open a search result page of some urls, not just the homepages.
for examples,
I search stack overflow in google. The url is here, but the return page is google homepage.Is it possible to get the result page directly? I want to scratch some result pages. If I just open the homepage then input the keywords to get the result pages, I think this way should be very slow.
Thank you for your answers.
from selenium import selenium
url ='http://www.google.com/search?hl=en&source=hp&q=stack+overflow&aq=o&aqi=&aql=&oq=&gs_rfai='
sel = selenium('localhost', 4444, '*firefox', url)
sel.start()
sel.open('/')
sel.wait_for_page_to_load(10000)
| [
"You should change your code:\nfrom selenium import selenium\nurl ='http://www.google.com/'\nsel = selenium('localhost', 4444, '*firefox', url)\nsel.start()\nsel.open('/search?hl=en&source=hp&q=stack+overflow&aq=o&aqi=&aql=&oq=&gs_rfai=')\nsel.wait_for_page_to_load(10000)\n\nSo your url is pointing to the start pag... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0003456470_python_selenium_selenium_rc.txt |
Q:
Remove duplicate rows from a large file in Python
I've a csv file that I want to remove duplicate rows from, but it's too large to fit into memory. I found a way to get it done, but my guess is that it's not the best way.
Each row contains 15 fields and several hundred characters, and all fields are needed to determine uniqueness. Instead of comparing the entire row to find a duplicate, I'm comparing hash(row-as-a-string) in an attempt to save memory. I set a filter that partitions the data into a roughly equal number of rows (e.g. days of the week), and each partition is small enough that a lookup table of hash values for that partition will fit in memory. I pass through the file once for each partition, checking for unique rows and writing them out to a second file (pseudo code):
import csv
headers={'DayOfWeek':None, 'a':None, 'b':None}
outs=csv.DictWriter(open('c:\dedupedFile.csv','wb')
days=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
outs.writerows(headers)
for day in days:
htable={}
ins=csv.DictReader(open('c:\bigfile.csv','rb'),headers)
for line in ins:
hvalue=hash(reduce(lambda x,y:x+y,line.itervalues()))
if line['DayOfWeek']==day:
if hvalue in htable:
pass
else:
htable[hvalue]=None
outs.writerow(line)
One way I was thinking to speed this up is by finding a better filter to reduce the number of passes necessary. Assuming the length of the rows is uniformly distributed, maybe instead of
for day in days:
and
if line['DayOfWeek']==day:
we have
for i in range(n):
and
if len(reduce(lambda x,y:x+y,line.itervalues())%n)==i:
where 'n' as small as memory will allow. But this is still using the same method.
Wayne Werner provided a good practical solution below; I was curious if there was better/faster/simpler way to do this from an algorithm perspective.
P.S. I'm limited to Python 2.5.
A:
If you want a really simple way to do this, just create a sqlite database:
import sqlite3
conn = sqlite3.connect('single.db')
cur = conn.cursor()
cur.execute("""create table test(
f1 text,
f2 text,
f3 text,
f4 text,
f5 text,
f6 text,
f7 text,
f8 text,
f9 text,
f10 text,
f11 text,
f12 text,
f13 text,
f14 text,
f15 text,
primary key(f1, f2, f3, f4, f5, f6, f7,
f8, f9, f10, f11, f12, f13, f14, f15))
"""
conn.commit()
#simplified/pseudo code
for row in reader:
#assuming row returns a list-type object
try:
cur.execute('''insert into test values(?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?)''', row)
conn.commit()
except IntegrityError:
pass
conn.commit()
cur.execute('select * from test')
for row in cur:
#write row to csv file
Then you wouldn't have to worry about any of the comparison logic yourself - just let sqlite take care of it for you. It probably won't be much faster than hashing the strings, but it's probably a lot easier. Of course you'd modify the type stored in the database if you wanted, or not as the case may be. Of course since you're already converting the data to a string you could just have one field instead. Plenty of options here.
A:
You are basically doing a merge sort, and removing duplicated entries.
Breaking the input into memory-sized pieces, sorting each of piece, then merging the pieces while removing duplicates is a sound idea in general.
Actually, up to a couple of gigs I would let the virtual memory system handle it and just write:
input = open(infilename, 'rb')
output = open(outfile, 'wb')
for key, group in itertools.groupby(sorted(input)):
output.write(key)
A:
Your current method is not guaranteed to work properly.
Firstly, there is the small probability that two lines that are actually different can produce the same hash value. hash(a) == hash(b) does not always mean that a == b
Secondly, you are making the probability higher with your "reduce/lambda" caper:
>>> reduce(lambda x,y: x+y, ['foo', '1', '23'])
'foo123'
>>> reduce(lambda x,y: x+y, ['foo', '12', '3'])
'foo123'
>>>
BTW, wouldn't "".join(['foo', '1', '23']) be somewhat clearer?
BTW2, why not use a set instead of a dict for htable?
Here's a practical solution: get the "core utils" package from the GnuWin32 site, and install it. Then:
write a copy of your file without the headings to (say) infile.csv
c:\gnuwin32\bin\sort --unique -ooutfile.csv infile.csv
read outfile.csv and write a copy with the headings prepended
For each of steps 1 & 3, you could use a Python script, or some of the other GnuWin32 utilities (head, tail, tee, cat, ...).
A:
Your original solution is slightly incorrect: you could have different lines hashing to the same value (a hash collision), and your code would leave one of them out.
In terms of algorithmic complexity, if you're expecting relatively few duplicates, I think the fastest solution would be to scan the file line by line, adding the hash of each line (as you did), but also storing the location of that line. Then when you encounter a duplicate hash, seek to the original place to make sure that it is a duplicate and not just a hash collision, and if so, seek back and skip the line.
By the way, if the CSV values are normalized (i.e., records are considered equal iff the corresponding CSV rows are equivalent byte-for-byte), you need not involve CSV parsing here at all, just deal with plain text lines.
A:
Since I suppose you'll have to do this on a somewhat regular basis (or you'd have hacked a once-over script), and you mentioned you were interested in a theoretical solution, here's a possibility.
Read the input lines into B-Trees, ordered by each input line's hash value, writing them to disk when memory fills. We take care to store, on the B-Trees, the original lines attached to the hash (as a set, since we only care about unique lines). When we read a duplicate element, we check the lines set on the stored element and add it if it's a new line that happens to hash to the same value.
Why B-Trees? They requires less disk reads when you only can (or want) to read parts of them to memory. The degree (number of children) on each node depends on the available memory and number of lines, but you don't want to have too many nodes.
Once we have those B-Trees on disk, we compare the lowest element from each of them. We remove the lowest of all, from all B-Trees that have it. We merge their lines sets, meaning that we have no duplicates left for those lines (and also that we have no more lines that hash to that value). We then write the lines from this merge into the output csv structure.
We can separate half of the memory for reading the B-Trees, and half to keep the output csv in memory for some time. We flush the csv to disk when its half is full, appending to whatever has already been written. How much of each B-Tree we read on each step can be roughly calculated by (available_memory / 2) / number_of_btrees, rounded so we read full nodes.
In pseudo-Python:
ins = DictReader(...)
i = 0
while ins.still_has_lines_to_be_read():
tree = BTree(i)
while fits_into_memory:
line = ins.readline()
tree.add(line, key=hash)
tree.write_to_disc()
i += 1
n_btrees = i
# At this point, we have several (n_btres) B-Trees on disk
while n_btrees:
n_bytes = (available_memory / 2) / n_btrees
btrees = [read_btree_from_disk(i, n_bytes)
for i in enumerate(range(n_btrees))]
lowest_candidates = [get_lowest(b) for b in btrees]
lowest = min(lowest_candidates)
lines = set()
for i in range(number_of_btrees):
tree = btrees[i]
if lowest == lowest_candidates[i]:
node = tree.pop_lowest()
lines.update(node.lines)
if tree.is_empty():
n_btrees -= 1
if output_memory_is_full or n_btrees == 0:
outs.append_on_disk(lines)
A:
How about using heapq module to read pieces of file up to memory limit and write them out the sorted pieces (heapq keeps things always in sorted order).
Or you could catch the first word in line and divide the file to pieces by that. Then you can read the lines (maybe do ' '.join(line.split()) to unify the spacing/tabs in line if it is OK to change spacing) in set in alphabetic order clearing the set between the pieces (set removes duplicates) to get things half sorted (set is not in order, if you want you can read in to heap and write out to get sorted order, last occurrence in set replacing old values as you go.) Alternatively you can also sort the piece and remove duplicate lines with Joe Koberg's groupby solution. Lastly you can join pieces back together (you can of course do the writing as you go piece by piece to final file during sorting of pieces)
| Remove duplicate rows from a large file in Python | I've a csv file that I want to remove duplicate rows from, but it's too large to fit into memory. I found a way to get it done, but my guess is that it's not the best way.
Each row contains 15 fields and several hundred characters, and all fields are needed to determine uniqueness. Instead of comparing the entire row to find a duplicate, I'm comparing hash(row-as-a-string) in an attempt to save memory. I set a filter that partitions the data into a roughly equal number of rows (e.g. days of the week), and each partition is small enough that a lookup table of hash values for that partition will fit in memory. I pass through the file once for each partition, checking for unique rows and writing them out to a second file (pseudo code):
import csv
headers={'DayOfWeek':None, 'a':None, 'b':None}
outs=csv.DictWriter(open('c:\dedupedFile.csv','wb')
days=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
outs.writerows(headers)
for day in days:
htable={}
ins=csv.DictReader(open('c:\bigfile.csv','rb'),headers)
for line in ins:
hvalue=hash(reduce(lambda x,y:x+y,line.itervalues()))
if line['DayOfWeek']==day:
if hvalue in htable:
pass
else:
htable[hvalue]=None
outs.writerow(line)
One way I was thinking to speed this up is by finding a better filter to reduce the number of passes necessary. Assuming the length of the rows is uniformly distributed, maybe instead of
for day in days:
and
if line['DayOfWeek']==day:
we have
for i in range(n):
and
if len(reduce(lambda x,y:x+y,line.itervalues())%n)==i:
where 'n' as small as memory will allow. But this is still using the same method.
Wayne Werner provided a good practical solution below; I was curious if there was better/faster/simpler way to do this from an algorithm perspective.
P.S. I'm limited to Python 2.5.
| [
"If you want a really simple way to do this, just create a sqlite database:\nimport sqlite3\nconn = sqlite3.connect('single.db')\ncur = conn.cursor()\ncur.execute(\"\"\"create table test(\nf1 text,\nf2 text,\nf3 text,\nf4 text,\nf5 text,\nf6 text,\nf7 text,\nf8 text,\nf9 text,\nf10 text,\nf11 text,\nf12 text,\nf13 ... | [
13,
6,
2,
1,
0,
0
] | [] | [] | [
"duplicates",
"python"
] | stackoverflow_0003452832_duplicates_python.txt |
Q:
python analyse 2 logfiles
I have 2 large logfiles. I want to see if a device is in a but not b and vice versa (exclude lines where the device is common) the files look like this example.
04/09/2010,13:11:52,Authen OK,user1,Default Group,00-24-2B-A1-08-88,29,10.1.1.1,(Default),,,,,,13,EAP-TLS,,device1,
04/19/2010,15:35:24,Authen OK,user2,Default Group,00-24-2B-A1-05-EA,29,10.1.1.2,(Default),,,,,,13,EAP-TLS,,device2,
04/09/2010,13:11:52,Authen OK,user3,Default Group,00-24-2B-A1-08-88,29,10.1.1.3,(Default),,,,,,13,EAP-TLS,,device3,
04/19/2010,15:35:24,Authen OK,user4,Default Group,00-24-2B-A1-05-EA,29,10.1.1.4,(Default),,,,,,13,EAP-TLS,,device4,
to reiterate, I need device (field [-2]) and IP (field [7]) for each device that is in logfile a but not b, and is in b but not a
Here's what I've done so far, but seems a little clunky and is very slow (each file has about 400K lines). I'm cross referring twice. Can anyone suggest efficiencies please? Perhaps I am using the wrong logic??
chst={}
chbs={}
for i,line in enumerate(open('chst.txt').readlines()):
line=line.split(',')
chst[line[-2]+','+str(i)]=','.join(line)
for i,line in enumerate(open('chbs.txt').readlines()):
line=line.split(',')
chbs[line[-2]+','+str(i)]='.'.join(line)
print "these lines are in CHST but not in CHBS"
for a in chst:
if a.split(',')[0] not in str(chbs.values()):
line=chst[a].split(',')
print line[-2], line[7]
print "\nthese lines are in CHBS but not in CHST"
for a in chbs:
if a.split(',')[0] not in str(chst.values()):
line=chbs[a].split(',')
print line[-2], line[7]
A:
You are looking for a symmetric difference:
chst = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ) for line in open( ... ) }
chbs = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ) for line in open( ... ) }
diff = chst ^ chbs
If you need the asymmetric differences, use -:
chst - chbs # tuples in chst but not in chbs
chbs - chst # tuples in chbs but not in chst
If you need the actual line, instead of a tuple ( device, IP ) you can use dictionaries instead of sets:
chst = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ): line for line in open( ... ) }
chbs = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ): line for line in open( ... ) }
diff = chst.items( ) ^ bar.items( )
This works because dict.items( ) returns a view on the items, which has setlike properties. Note that this is called dict.viewitems( ) in Python 2.x.
A:
There's a bug in line 9 where you are doing ='.'.join(line) instead of =','.join(line) i.e. a dot in the quotes instead of a comma. Or maybe the lines in chbs should be split on dots instead of commas later.
At the moment if there are three lines for device7 is in chbs but not chst the script will tell you three times, but your description of the problem implies that you don't need to know how many times it appears. Do you really want that or is a single report OK for multiple occurrences? In that case you could simplify it by just using the device name as the dictionary key and checking if the other dictionary has that key.
Also at the moment you're recording the line numbers, but not really using them. If you do need to know how many times a device appears why not report that instead of having to count them? In which case when adding a device key to the dictionary first check if it's already there and if so increment a counter (perhaps in another dictionary also keyed by the device name).
| python analyse 2 logfiles | I have 2 large logfiles. I want to see if a device is in a but not b and vice versa (exclude lines where the device is common) the files look like this example.
04/09/2010,13:11:52,Authen OK,user1,Default Group,00-24-2B-A1-08-88,29,10.1.1.1,(Default),,,,,,13,EAP-TLS,,device1,
04/19/2010,15:35:24,Authen OK,user2,Default Group,00-24-2B-A1-05-EA,29,10.1.1.2,(Default),,,,,,13,EAP-TLS,,device2,
04/09/2010,13:11:52,Authen OK,user3,Default Group,00-24-2B-A1-08-88,29,10.1.1.3,(Default),,,,,,13,EAP-TLS,,device3,
04/19/2010,15:35:24,Authen OK,user4,Default Group,00-24-2B-A1-05-EA,29,10.1.1.4,(Default),,,,,,13,EAP-TLS,,device4,
to reiterate, I need device (field [-2]) and IP (field [7]) for each device that is in logfile a but not b, and is in b but not a
Here's what I've done so far, but seems a little clunky and is very slow (each file has about 400K lines). I'm cross referring twice. Can anyone suggest efficiencies please? Perhaps I am using the wrong logic??
chst={}
chbs={}
for i,line in enumerate(open('chst.txt').readlines()):
line=line.split(',')
chst[line[-2]+','+str(i)]=','.join(line)
for i,line in enumerate(open('chbs.txt').readlines()):
line=line.split(',')
chbs[line[-2]+','+str(i)]='.'.join(line)
print "these lines are in CHST but not in CHBS"
for a in chst:
if a.split(',')[0] not in str(chbs.values()):
line=chst[a].split(',')
print line[-2], line[7]
print "\nthese lines are in CHBS but not in CHST"
for a in chbs:
if a.split(',')[0] not in str(chst.values()):
line=chbs[a].split(',')
print line[-2], line[7]
| [
"You are looking for a symmetric difference:\nchst = { ( line.split( \",\" )[ -2 ], line.split( \",\" )[ 7 ] ) for line in open( ... ) }\nchbs = { ( line.split( \",\" )[ -2 ], line.split( \",\" )[ 7 ] ) for line in open( ... ) }\n\ndiff = chst ^ chbs\n\nIf you need the asymmetric differences, use -:\nchst - chbs # ... | [
1,
0
] | [] | [] | [
"logfiles",
"python"
] | stackoverflow_0003456651_logfiles_python.txt |
Q:
Python importing modules that all import another module that is the same
What i want to is, I have foo.py it imports classes from bar1, bar2, and they both need bar3, e.g.
foo.py
from src import *
...
src/ __ init__.py
from bar1 import specialSandwichMaker
from bar2 import specialMuffinMaker
src/bar1.py
import bar3
class specialSandwichMaker(bar3.sandwichMaker)
...
src/bar2.py
import bar3
class specialMuffinMaker(bar3.muffinMaker)
...
is there a more efficient way to make bar3 available to the bar1 and bar2 files without having them directly import it?
A:
This is fully efficient; when importing a module Python will add it to sys.modules. import statements first check this dictionary (which is fast because dictionary lookups are fast) to see whether the module has been imported already. So in this case, bar1 will import bar3 and add it to sys.modules. Then bar2 will use the bar3 that has already been imported.
You can verify this with:
import sys
print( sys.modules )
Note that from src import * is bad code and you shouldn't use it. Either import src and use src.specialSandwichMaker references, or from src import specialSandwichMaker. This is because modules shouldn't pollute each other's namespaces -- if you do from src import *, all the global variables defined in src will appear in your namespace too. This is Bad.
A:
you should define all as specified in
http://docs.python.org/tutorial/modules.html#importing-from-a-package
| Python importing modules that all import another module that is the same | What i want to is, I have foo.py it imports classes from bar1, bar2, and they both need bar3, e.g.
foo.py
from src import *
...
src/ __ init__.py
from bar1 import specialSandwichMaker
from bar2 import specialMuffinMaker
src/bar1.py
import bar3
class specialSandwichMaker(bar3.sandwichMaker)
...
src/bar2.py
import bar3
class specialMuffinMaker(bar3.muffinMaker)
...
is there a more efficient way to make bar3 available to the bar1 and bar2 files without having them directly import it?
| [
"This is fully efficient; when importing a module Python will add it to sys.modules. import statements first check this dictionary (which is fast because dictionary lookups are fast) to see whether the module has been imported already. So in this case, bar1 will import bar3 and add it to sys.modules. Then bar2 will... | [
8,
1
] | [] | [] | [
"python"
] | stackoverflow_0003456874_python.txt |
Q:
Python subprocess.Popen communicate through a pipeline
I want to be able to use Popen.communicate and have the stdout logged to a file (in addition to being returned from communicate().
This does what I want - but is it really a good idea?
cat_task = subprocess.Popen(["cat"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
tee_task = subprocess.Popen(["tee", "-a", "/tmp/logcmd"], stdin=cat_task.stdout,
stdout = subprocess.PIPE, close_fds=True)
cat_task.stdout = tee_task.stdout #since cat's stdout is consumed by tee, read from tee.
cat_task.communicate("hello there")
('hello there', None)
Any issues with this, looking at communicate's impl it looks good. But is there a nicer way?
A:
Depending on your definition of "nicer", I would say that the following is probably nicer in the sense that it avoids having an additional tee process:
import subprocess
def logcommunicate(self, s):
std = self.oldcommunicate(s)
self.logfilehandle.write(std[0])
return std
subprocess.Popen.oldcommunicate = subprocess.Popen.communicate
subprocess.Popen.communicate = logcommunicate
logfh = open("/tmp/communicate.log", "a")
proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
proc.logfilehandle = logfh
result = proc.communicate("hello there\n")
print result
In a nutshell, it provides a wrapper for communicate() that writes stdout to a file handle of your choice, and then returns the original tuple for you to use. I've omitted exception handling; you should probably add that if the program is more critical. Also, if you expect to create several Popen objects and want them all to log to the same file, you should probably arrange for logcommunicate() to be thread-safe (synchronised per file handle). You can easily extend this solution to write to separate files for stdout and stderr.
Note that if you expect to pass a lot of data back and forth, then communicate() might not be the best option since it buffers everything in memory.
| Python subprocess.Popen communicate through a pipeline | I want to be able to use Popen.communicate and have the stdout logged to a file (in addition to being returned from communicate().
This does what I want - but is it really a good idea?
cat_task = subprocess.Popen(["cat"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
tee_task = subprocess.Popen(["tee", "-a", "/tmp/logcmd"], stdin=cat_task.stdout,
stdout = subprocess.PIPE, close_fds=True)
cat_task.stdout = tee_task.stdout #since cat's stdout is consumed by tee, read from tee.
cat_task.communicate("hello there")
('hello there', None)
Any issues with this, looking at communicate's impl it looks good. But is there a nicer way?
| [
"Depending on your definition of \"nicer\", I would say that the following is probably nicer in the sense that it avoids having an additional tee process:\nimport subprocess\n\ndef logcommunicate(self, s):\n std = self.oldcommunicate(s)\n self.logfilehandle.write(std[0])\n return std\n\nsubprocess.Popen.ol... | [
1
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0003456692_popen_python_subprocess.txt |
Q:
How to save a webpage by seleniumRC
I use seleniumRC to open a url, then how to save this web page? How to realize it like urllib.urlretrieve do it? But urllib can't operate javascript in the page. One more question: Will it save the whole page with what I see as seleniumRC open it?
A:
It sounds like you are confusing two very different libraries.
urllib:
This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames.
You can use python's urllib library to retrieve the raw markup from a valid URL. The library doesn't invoke any embedded javascript on the page, because the library never attempts to parse or render anything.
Selenium RC:
Selenium Remote Control (RC) is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser.
Selenium RC is used to automate testing. Execution of your tests occurs in a web browser via javascript, but this is a testing suite — you receive information about the status of your tests. Selenium RC does not provide any functionality to save an image of the rendered page.
Unless I've misinterpreted your question, you seem to be looking for a library that will allow you to retrieve an image of a rendered HTML page (including javascript DOM manipulation). If this is indeed the case, I would suggest looking into PyWebShot, which seems to provide exactly that functionality. You can view screenshots of it in action here (along with some additional info about it).
If it doesn't necessarily need to be a python library, there are a number of web services around that provide screenshots:
IE Web Renderer
Browsershots
BrowsrCamp
BrowserCam
| How to save a webpage by seleniumRC | I use seleniumRC to open a url, then how to save this web page? How to realize it like urllib.urlretrieve do it? But urllib can't operate javascript in the page. One more question: Will it save the whole page with what I see as seleniumRC open it?
| [
"It sounds like you are confusing two very different libraries.\nurllib:\n\nThis module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. ... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0003456852_python_selenium_selenium_rc.txt |
Q:
Difference between simple Python function call and wrapping it in cProfile.run()
I have a rather simple Python script that contains a function call like
f(var, other_var)
i.e. a function that gets several parameters. All those parameters can be accessed within f and have values.
When I instead call
cProfile.run('f(var, other_var)')
it fails with the error message:
NameError: "name 'var' is not defined"
Python version is
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
What's going on here?
A:
This is because cProfile attempts to exec the code you pass it as a string, and fails because, well, var is not defined in that piece of code! It is using the variables in the scope of the call to run(), but since you haven't told cProfile about them it doesn't know to use them. Use runctx instead, since it allows you to pass in the locals and globals dictionaries to use for the execed code:
cProfile.runctx( "...", globals(), locals() )
| Difference between simple Python function call and wrapping it in cProfile.run() | I have a rather simple Python script that contains a function call like
f(var, other_var)
i.e. a function that gets several parameters. All those parameters can be accessed within f and have values.
When I instead call
cProfile.run('f(var, other_var)')
it fails with the error message:
NameError: "name 'var' is not defined"
Python version is
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
What's going on here?
| [
"This is because cProfile attempts to exec the code you pass it as a string, and fails because, well, var is not defined in that piece of code! It is using the variables in the scope of the call to run(), but since you haven't told cProfile about them it doesn't know to use them. Use runctx instead, since it allows... | [
9
] | [] | [] | [
"profiler",
"python",
"python_2.6"
] | stackoverflow_0003457129_profiler_python_python_2.6.txt |
Q:
Comparing dates and times in different formats using Python
I have lines of the following format in a file.
Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z
I need to create a function that has two inputs: time and date in the following formats Time: HH:MM and date as mmddyyyy. (These are strings). Now the function needs to read this line and see if the the input date and time, lies between DateStart(20100629T11000) and DateEnd(20100629T120000). How do i deal with this since the format of date and time in the input and the line are in two formats?
A:
You can parse a string into a datetime with strptime:
>>> datetime.datetime.strptime('20100629T110000', '%Y%m%dT%H%M%S')
datetime.datetime(2010, 6, 29, 11, 0)
>>> datetime.datetime.strptime('23:45 06192005', '%H:%M %m%d%Y')
datetime.datetime(2005, 6, 19, 23, 45)
And then you can compare (<, <=, etc) the two datetimes.
A:
To handle dates and times, use Python's datetime module. The datetime class in that module has a method for reading datetimes from strings, called strptime. So you can do:
# read the file, so that:
strStart = "20100629T110000"
strEnd = "20100629T120000"
imTime = "HH:MM"
inDate = "mmddyyyy"
import datetime
dateStart = datetime.datetime.strptime( strStart, "%Y%m%dT%H%M%S" )
dateEnd = datetime.datetime.strptime( strEnd, "%Y%m%dT%H%M%S" )
dateIn = datetime.datetime.strptime( inDate + inTime, "%m%d%Y%H:%M" )
assert dateStart < dateIn < dateEnd
N.B. You can use csv to read the file.
A:
Use the datetime class inside the datetime module. Here is a function that does what you need, though you might need to adjust boundary conditions:
from datetime import datetime
def f(row, datestr, timestr):
tmp = row.split(";")
start = datetime.strptime(tmp[5], "%Y%m%dT%H%M%S")
end = datetime.strptime(tmp[7], "%Y%m%dT%H%M%S")
mytimestamp = datetime.strptime(datestr+timestr, "%d%m%Y%H:%M")
if (start < mytimestamp and mytimestamp < end):
print "inside"
else:
print "not inside"
>>> f("Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z", "29062010", "11:00")
not inside
>>> f("Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z", "29062010", "11:30")
inside
| Comparing dates and times in different formats using Python | I have lines of the following format in a file.
Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z
I need to create a function that has two inputs: time and date in the following formats Time: HH:MM and date as mmddyyyy. (These are strings). Now the function needs to read this line and see if the the input date and time, lies between DateStart(20100629T11000) and DateEnd(20100629T120000). How do i deal with this since the format of date and time in the input and the line are in two formats?
| [
"You can parse a string into a datetime with strptime:\n>>> datetime.datetime.strptime('20100629T110000', '%Y%m%dT%H%M%S')\ndatetime.datetime(2010, 6, 29, 11, 0)\n>>> datetime.datetime.strptime('23:45 06192005', '%H:%M %m%d%Y')\ndatetime.datetime(2005, 6, 19, 23, 45)\n\nAnd then you can compare (<, <=, etc) the two... | [
4,
1,
1
] | [] | [] | [
"date",
"python",
"time"
] | stackoverflow_0003457452_date_python_time.txt |
Q:
Elegant way to create a dictionary of pairs, from a list of tuples?
I have defined a tuple thus:
(slot, gameid, bitrate)
and created a list of them called myListOfTuples. In this list might be tuples containing the same gameid.
E.g. the list can look like:
[
(1, "Solitaire", 1000 ),
(2, "Diner Dash", 22322 ),
(3, "Solitaire", 0 ),
(4, "Super Mario Kart", 854564 ),
... and so on.
]
From this list, I need to create a dictionary of pairs - ( gameId, bitrate), where the bitrate for that gameId is the first one that I came across for that particular gameId in myListOfTuples.
E.g. From the above example - the dictionary of pairs would contain only one pair with gameId "Solitaire" : ("Solitaire", 1000 ) because 1000 is the first bitrate found.
NB. I can create a set of unique games with this:
uniqueGames = set( (e[1] for e in myListOfTuples ) )
A:
For python2.6
dict(x[1:] for x in reversed(myListOfTuples))
If you have Python2.7 or 3.1, you can use katrielalex's answer
A:
{ gameId: bitrate for _, gameId, bitrate in reversed( myListOfTuples ) }.items( )
(This is a view, not a set. It has setlike operations, but if you need a set, cast it to one.)
Are you sure you want a set, not a dictionary of gameId: bitrate? The latter seems to me to be a more natural data structure for this problem.
| Elegant way to create a dictionary of pairs, from a list of tuples? | I have defined a tuple thus:
(slot, gameid, bitrate)
and created a list of them called myListOfTuples. In this list might be tuples containing the same gameid.
E.g. the list can look like:
[
(1, "Solitaire", 1000 ),
(2, "Diner Dash", 22322 ),
(3, "Solitaire", 0 ),
(4, "Super Mario Kart", 854564 ),
... and so on.
]
From this list, I need to create a dictionary of pairs - ( gameId, bitrate), where the bitrate for that gameId is the first one that I came across for that particular gameId in myListOfTuples.
E.g. From the above example - the dictionary of pairs would contain only one pair with gameId "Solitaire" : ("Solitaire", 1000 ) because 1000 is the first bitrate found.
NB. I can create a set of unique games with this:
uniqueGames = set( (e[1] for e in myListOfTuples ) )
| [
"For python2.6 \ndict(x[1:] for x in reversed(myListOfTuples))\n\nIf you have Python2.7 or 3.1, you can use katrielalex's answer\n",
"{ gameId: bitrate for _, gameId, bitrate in reversed( myListOfTuples ) }.items( )\n\n(This is a view, not a set. It has setlike operations, but if you need a set, cast it to one.)\... | [
10,
4
] | [] | [] | [
"python"
] | stackoverflow_0003457673_python.txt |
Q:
nagare framework on gae?
anyone using nagare framework on google app engine ?
it seems interesting, but i could not find any documentaiton on how to use it on
google app engine, as it uses stackless python.
so any chances of its running on google app engine ?
also, how stack less python differ from normal python ?
thanks.
links :
Nagare Framework
Stackless python
A:
I currently have a not-yet-released, prototype version of Nagare for GAE (you can see the canonical Counter example at http://nagareproject.appspot.com/)
Here are the 3 Nagare components not working on GAE, with their workarounds in this prototype:
Stackless Python:
Problem: GAE is only pure vanilla CPython
Solution: well, use only pure Python
Limitation: in Nagare, Stackless Python is used to obtain continuation objects. Without Stackless, we lose the call()/answer() feature of Nagare. But note that call()/on_answer() is still working.
Lxml:
Problem: C module not accepted on GAE
Solution: HTML generation rewrote using only ElementTree
Limitation: no more advance Lxml features like XSL or complex XPATH expressions
PEAK-Rules:
Problem: standard AST tree management removed on GAE
Solution: rules management for HTML/JS generation rewrote
Limitation: the security and URL dispatch rules must be written by the developer without the help of generic methods
So, this version of Nagare is pretty much working fine on GAE. And I dare to say that, even with these limitations, Nagare still stay on GAE a better programming environement than the others Python frameworks.
If you want to test it, send a message in the Nagare users group or send me a personal mail to alain.poirier at net-ng.com
A:
If it has a hard dependency on Stackless, it won't run on AppEngine. AE has its own Python runtime. If it doesn't leverage any of Stackless's non-standard extensions to Python, it might work, but I'd say that your chances aren't very good that it would just work.
| nagare framework on gae? | anyone using nagare framework on google app engine ?
it seems interesting, but i could not find any documentaiton on how to use it on
google app engine, as it uses stackless python.
so any chances of its running on google app engine ?
also, how stack less python differ from normal python ?
thanks.
links :
Nagare Framework
Stackless python
| [
"I currently have a not-yet-released, prototype version of Nagare for GAE (you can see the canonical Counter example at http://nagareproject.appspot.com/)\nHere are the 3 Nagare components not working on GAE, with their workarounds in this prototype:\n\nStackless Python:\n\nProblem: GAE is only pure vanilla CPython... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"python_stackless"
] | stackoverflow_0003449787_google_app_engine_python_python_stackless.txt |
Q:
Can't read file in__init__
I am a newbe to Python.
I have tried to create a class, named ic0File.
Here is what I get when I use it (Python 3.1)
>>> import sys
>>> sys.path.append('/remote/us01home15/ldagan/python/')
>>> import ic0File
>>> a=ic0File.ic0File('as_client/nohpp.ic0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ic0File.py", line 7, in __init__
print ("".join(self.lines))
NameError: global name 'infile' is not defined
The class code is:
class ic0File:
def __init__(self,filename):
self.infile = open(filename, 'r')
import sys
import re
self.lines=self.infile.readlines() #reading the lines
print ("".join(self.lines)
Thanks,
A:
To reload a module (e.g. if you have modified the code), use reload(). In your case:
reload( ic0file )
In Python 3, reload was moved to the imp library:
import imp
imp.reload( ic0file )
A:
As other users have pointed out, the code that actually raised that exception would be helpful, but my guess is that you're trying to access the infile attribute of a ic0File as if it was actually a variable.
You've probably written something like this:
self.lines = infile.readlines() #reading the lines
instead of:
self.lines = self.infile.readlines() #reading the lines
in one of the methods of ic0File. Unlike in other languages, object attributes don't become local variables in said object's methods.
| Can't read file in__init__ | I am a newbe to Python.
I have tried to create a class, named ic0File.
Here is what I get when I use it (Python 3.1)
>>> import sys
>>> sys.path.append('/remote/us01home15/ldagan/python/')
>>> import ic0File
>>> a=ic0File.ic0File('as_client/nohpp.ic0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ic0File.py", line 7, in __init__
print ("".join(self.lines))
NameError: global name 'infile' is not defined
The class code is:
class ic0File:
def __init__(self,filename):
self.infile = open(filename, 'r')
import sys
import re
self.lines=self.infile.readlines() #reading the lines
print ("".join(self.lines)
Thanks,
| [
"To reload a module (e.g. if you have modified the code), use reload(). In your case:\nreload( ic0file )\n\nIn Python 3, reload was moved to the imp library:\nimport imp\nimp.reload( ic0file )\n\n",
"As other users have pointed out, the code that actually raised that exception would be helpful, but my guess is th... | [
0,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003457302_class_python.txt |
Q:
Make an installer for python project
I downloaded an open source project http://gmapcatcher.googlecode.com/files/GMapCatcher-0.7.2.0.tar.gz and I am trying to modify a few things in the code but don't know how to test the code!
I tried to make an installer for the project but nothing worked till now maybe I didn't follow the right steps or I am missing somthing.
my question is how can I modify the code and test it ? and how can I make an installer for this project (I know there is an installer already in google but I want to make it myself).
A:
Looks like the package has a setup.py for the use with distutils. The setup.py works kind of like Makefile for python. The way you use it is (in the directory where setup.py is located:
$ python setup.py command
Where "command" is... well... a command. Type
$ python setup.py --help
for more information. The two basic commands are build and install. install installs, as the name suggests, the package to your system. It is not probably going to do anything like create shortcuts on your desktop or anything like that. It simply installs the Python package into your Python installation. Judging by the contents of setup.py, it seems they're somehow using py2exe (google it; being a newbie I can only include one hyperlink in my answer) to prepare the Windows installer.
To simply run the software, however, it seems all you need to do is to unpack it and do
$ python maps.py
in the package's root directory - provided you have all the necessary dependencies already installed, of course.
| Make an installer for python project | I downloaded an open source project http://gmapcatcher.googlecode.com/files/GMapCatcher-0.7.2.0.tar.gz and I am trying to modify a few things in the code but don't know how to test the code!
I tried to make an installer for the project but nothing worked till now maybe I didn't follow the right steps or I am missing somthing.
my question is how can I modify the code and test it ? and how can I make an installer for this project (I know there is an installer already in google but I want to make it myself).
| [
"Looks like the package has a setup.py for the use with distutils. The setup.py works kind of like Makefile for python. The way you use it is (in the directory where setup.py is located:\n$ python setup.py command\n\nWhere \"command\" is... well... a command. Type\n$ python setup.py --help\n\nfor more information. ... | [
3
] | [] | [] | [
"open_source",
"python",
"windows"
] | stackoverflow_0003457130_open_source_python_windows.txt |
Q:
Concurrency Testing For A Web Service Using Python
I have a web service that is required to handle significant concurrent utilization and volume and I need to test it. Since the service is fairly specialized, it does not lend itself well to a typical testing framework. The test would need to simulate multiple clients concurrently posting to a URL, parsing the resulting Http response, checking that a database has been appropriately updated and making sure certain emails have been correctly sent/received.
The current opinion at my company is that I should write this framework using Python. I have never used Python with multiple threads before and as I was doing my research I came across the Global Interpreter Lock which seems to be the basis of most of Python's concurrency handling. It seems to me that the GIL would prevent Python from being able to achieve true concurrency even on a multi-processor machine. Is this true? Does this scenario change if I use a compiler to compile Python to native code? Am I just barking up the wrong tree entirely and is Python the wrong tool for this job?
A:
The Global Interpreter Lock prevents threads simultaneously executing Python code. This doesn't change when Python is compiled to bytecode, because the bytecode is still run by the Python interpreter, which will enforce the GIL. threading works by switching threads every sys.getcheckinterval() bytecodes.
This doesn't apply to multiprocessing, because it creates multiple Python processes instead of threads. You can have as many of those as your system will support, running truly concurrently.
So yes, you can do this with Python, either with threading or multiprocessing.
A:
you can use python's multiprocessing library to achieve this.
http://docs.python.org/library/multiprocessing.html
A:
Assuming general network conditions, as long you have sufficient system resources Python's regular threading module will allow you to simulate concurrent workload at an higher rate than any a real workload.
| Concurrency Testing For A Web Service Using Python | I have a web service that is required to handle significant concurrent utilization and volume and I need to test it. Since the service is fairly specialized, it does not lend itself well to a typical testing framework. The test would need to simulate multiple clients concurrently posting to a URL, parsing the resulting Http response, checking that a database has been appropriately updated and making sure certain emails have been correctly sent/received.
The current opinion at my company is that I should write this framework using Python. I have never used Python with multiple threads before and as I was doing my research I came across the Global Interpreter Lock which seems to be the basis of most of Python's concurrency handling. It seems to me that the GIL would prevent Python from being able to achieve true concurrency even on a multi-processor machine. Is this true? Does this scenario change if I use a compiler to compile Python to native code? Am I just barking up the wrong tree entirely and is Python the wrong tool for this job?
| [
"The Global Interpreter Lock prevents threads simultaneously executing Python code. This doesn't change when Python is compiled to bytecode, because the bytecode is still run by the Python interpreter, which will enforce the GIL. threading works by switching threads every sys.getcheckinterval() bytecodes.\nThis doe... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003458249_python.txt |
Q:
When while loop placed in wxPython events
I'm trying to write a GUI program grabbing specific contents from a webpage. The idea is when I hit the start button, the program should start extracting information from that page. And I want to add some code to check if connected to the Internet. If not, continue trying until connected.
So I just added the following code in the event, but found it didn't work. Also the whole program has to be closed in a forced way. Here's my code:
import urllib2
import time
InternetNotOn = True
while InternetNotOn:
try:
urllib2.urlopen("http://google.com")
InternetNotOn = False
print "Everyting is fine!"
except urllib2.URLError, e:
print "Error!"
time.sleep(10)
What could the problem be?
A:
When you have an event based program, the overall flow of the program is this:
while the-program-is-running:
wait-for-an-event
service-the-event
exit
Now, lets see what happens when service-the-event calls something with a (potentially) infinite loop:
while the-program-is-running:
wait-for-an-event
while the-internet-is-on:
do-something
exit
Do you see the problem? In the worse case your program may never call wait-for-an-event again because your loop is running.
Remember: the event loop is already an infinite loop, you don't need to add another infinite loop inside of it. Instead, take advantage of the existing loop. You can use wx.CallAfter or wx.CallLater to call a method which will cause your function to be called at the next iteration of the event loop.
Then, within your function you call wx.CallAfter or wx.CallLater again to cause it to again be called on the next iteration of the event loop.
A:
Instead of time.sleep(10) you can call wxApp::Yield and time.sleep(1) ten times.
Beware of reentrancy problems (e.g. pressing the start button again.). The start button could be dimmed while in the event handler.
But Bryan Oakley's solution is probably the better way.
| When while loop placed in wxPython events | I'm trying to write a GUI program grabbing specific contents from a webpage. The idea is when I hit the start button, the program should start extracting information from that page. And I want to add some code to check if connected to the Internet. If not, continue trying until connected.
So I just added the following code in the event, but found it didn't work. Also the whole program has to be closed in a forced way. Here's my code:
import urllib2
import time
InternetNotOn = True
while InternetNotOn:
try:
urllib2.urlopen("http://google.com")
InternetNotOn = False
print "Everyting is fine!"
except urllib2.URLError, e:
print "Error!"
time.sleep(10)
What could the problem be?
| [
"When you have an event based program, the overall flow of the program is this:\nwhile the-program-is-running:\n wait-for-an-event\n service-the-event\nexit\n\nNow, lets see what happens when service-the-event calls something with a (potentially) infinite loop: \nwhile the-program-is-running:\n wait-for-an... | [
4,
0
] | [] | [] | [
"event_handling",
"python",
"wxpython"
] | stackoverflow_0003458023_event_handling_python_wxpython.txt |
Q:
Reason for low Pylint ratings of Python standard library code
A friend told me about Pylint and just out of curiosity, I ran it against some of the standard library modules. To my surprise, the ratings were low. Here are a few runs:
os.py
Your code has been rated at 3.55/10
random.py
Your code has been rated at 4.74/10
I ran it on some more modules and the found the rating to be ~ 6 - 7.
I was wondering the reason behind this? Is Pylint broken or there are more factors to the rating than I am aware of? I am asking this question particularly cause I am new to Python and was depending on Pylint to help me improve my coding style :)
A:
Pylint's defaults are quite strict, and complain about things they should not. For example, if you use foo(**kwargs), you get a message about using "magic". Sometimes it seems as if pylint is looking at Python from a Java programmer's point of view.
You'd have to look at the specific messages and decide if you agree with them.
Other problems include not being able to do platform-specific conditionals. In os.py, it complains:
F:119: Unable to import 'riscos'
A:
Pylint was written long after the stdlib. And the stdlib does not adhere to strict naming conventions for instance (PEP008 is recent, wrt python). Key factors for getting "good" pylint ratings:
make sure your code writing style is conform to what Pylint is expecting (or tune Pylint to match your style / conventions). This includes function, variables, class, method names, spaces at various places, etc.
write Python code in an as static as convenient way, and avoid dynamic tricks.
write docstrings
Obviously, the standard library is not written to optimize Pylint's ratings of the modules.
Using Pylint will not necessarily improve your "coding style". It will however in a number of cases make your code more easy to understand, sometimes at the cost of some "pythonicity".
| Reason for low Pylint ratings of Python standard library code | A friend told me about Pylint and just out of curiosity, I ran it against some of the standard library modules. To my surprise, the ratings were low. Here are a few runs:
os.py
Your code has been rated at 3.55/10
random.py
Your code has been rated at 4.74/10
I ran it on some more modules and the found the rating to be ~ 6 - 7.
I was wondering the reason behind this? Is Pylint broken or there are more factors to the rating than I am aware of? I am asking this question particularly cause I am new to Python and was depending on Pylint to help me improve my coding style :)
| [
"Pylint's defaults are quite strict, and complain about things they should not. For example, if you use foo(**kwargs), you get a message about using \"magic\". Sometimes it seems as if pylint is looking at Python from a Java programmer's point of view.\nYou'd have to look at the specific messages and decide if yo... | [
13,
8
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0003355998_pylint_python.txt |
Q:
Using built-in type(,,) function to create a dynamic module
I'm trying to use the type(,,) function to dynamically build a module. The module creates classes representing templates, and I need a new class for every .tex file that lives in a particular folder. For instance, if I have a a4-page-template.tex file, I need to create a class called A4PageTemplate.
I can create the type easily enough using the type statement; what I have so far looks like this;
#
# dynamictypes.py
#
import os, re
_requiredEnd = "-template.tex"
_packageDir = "C:\\Users\\...";
def _getClassName(name):
return re.sub("-(.)", lambda m: m.group(1).upper() , name) + "Template"
for file in os.listdir(_packageDir):
if file.lower().endswith(_requiredEnd):
_fileWithoutExt = file[:-len(_requiredEnd)]
_className = _getClassName(_fileWithoutExt)
_newClass = type(_className, (object,), dict(template=file))
print _newClass
Note the penultimate line creates the type, and the print statement that follows it shows that a type has been created for each template;
<class 'dynamictypes.PandocA4BookTemplate'>
<class 'dynamictypes.PandocBookTemplate'>
<class 'dynamictypes.PandocCompactTemplate'>
However, when I use the module, I can't make use of the type; if I write this consumer script;
import dynamictypes
myTemplate = dynamictypes.PandocA4BookTemplate()
I get this error;
Traceback (most recent call last):
File "C:\Users\steve.cooper\Desktop\driver.py", line 3, in <module>
myTemplate = dynamictypes.PandocA4BookTemplate()
AttributeError: 'module' object has no attribute 'PandocA4BookTemplate'
Can you think of a way for me to add the type I've created to the module, so that it is a first-class part of the module?
A:
You have created the new class and assigned it to the global variable _newClass, but you're not storing this variable! Notice that if you do dynamictypes._newClass you will get the final type created.
You need to make a variable to hold each new class, as you create it:
globals()[ _className ] = _newClass
This registers _className as a global variable in the module, so that you can access it from outside.
By the way, your regex fails on a4-page-template.tex -- you get a4PageTemplate instead of A4PageTemplate.
| Using built-in type(,,) function to create a dynamic module | I'm trying to use the type(,,) function to dynamically build a module. The module creates classes representing templates, and I need a new class for every .tex file that lives in a particular folder. For instance, if I have a a4-page-template.tex file, I need to create a class called A4PageTemplate.
I can create the type easily enough using the type statement; what I have so far looks like this;
#
# dynamictypes.py
#
import os, re
_requiredEnd = "-template.tex"
_packageDir = "C:\\Users\\...";
def _getClassName(name):
return re.sub("-(.)", lambda m: m.group(1).upper() , name) + "Template"
for file in os.listdir(_packageDir):
if file.lower().endswith(_requiredEnd):
_fileWithoutExt = file[:-len(_requiredEnd)]
_className = _getClassName(_fileWithoutExt)
_newClass = type(_className, (object,), dict(template=file))
print _newClass
Note the penultimate line creates the type, and the print statement that follows it shows that a type has been created for each template;
<class 'dynamictypes.PandocA4BookTemplate'>
<class 'dynamictypes.PandocBookTemplate'>
<class 'dynamictypes.PandocCompactTemplate'>
However, when I use the module, I can't make use of the type; if I write this consumer script;
import dynamictypes
myTemplate = dynamictypes.PandocA4BookTemplate()
I get this error;
Traceback (most recent call last):
File "C:\Users\steve.cooper\Desktop\driver.py", line 3, in <module>
myTemplate = dynamictypes.PandocA4BookTemplate()
AttributeError: 'module' object has no attribute 'PandocA4BookTemplate'
Can you think of a way for me to add the type I've created to the module, so that it is a first-class part of the module?
| [
"You have created the new class and assigned it to the global variable _newClass, but you're not storing this variable! Notice that if you do dynamictypes._newClass you will get the final type created. \nYou need to make a variable to hold each new class, as you create it:\nglobals()[ _className ] = _newClass\n\nTh... | [
3
] | [] | [] | [
"metaprogramming",
"module",
"python",
"python_module"
] | stackoverflow_0003458671_metaprogramming_module_python_python_module.txt |
Q:
loop through list of dictionaries
i have a list of dictionaries. there are several points inside the list, some are multiple. When there is a multiple entry i want to calculate the average of the x and the y of this point. My problem is, that i don't know how to loop through the list of dictionaries to compare the ids of the points!
when i use something like that:
for i in list:
for j in list:
if i['id'] == j['id']:
point = getPoint(i['geom'])
....
sorry, the formating is a little bit tricky... the second loop is inside the first one...
i think it compares the first entry of the list, so it's the same... so i have to start in the second loop with the second entry, but i can't do that with i-1 because i is the hole dictionary...
Someone an idea?
thanks in advance!
for j in range(1, len(NEWPoint)):
if i['gid']==j['gid']:
allsamePoints.append(j)
for k in allsamePoints:
for l in range(1, len(allsamePoints)):
if k['gid']==l['gid']:
Point1 = k['geom']
Point2=l['geom']
X=(Point1.x()+Point2.x())/2
Y=(Point1.y()+Point2.y())/2
AVPoint = QgsPoint(X, Y)
NEWReturnList.append({'gid': j['gid'], 'geom': AVPoint})
del l
for m in NEWReturnList:
for n in range(1, len(NEWReturnList)):
if m['gid']==n['gid']:
Point1 = m['geom']
Point2=n['geom']
X=(Point1.x()+Point2.x())/2
Y=(Point1.y()+Point2.y())/2
AVPoint = QgsPoint(X, Y)
NEWReturnList.append({'gid': j['gid'], 'geom': AVPoint})
del n
else:
pass
ok, i think... at the moment thats more confusing :)...
A:
One way would be changing the way you store your points, because as you already noticed, it's hard to get what you want out of it.
A much more useful structure would be a dict where the id maps to a list of points:
from collections import defaultdict
points_dict = defaultdict(list)
# make the new dict
for point in point_list:
id = point["id"]
points_dict[id].append(point['geom'])
def avg( lst ):
""" average of a `lst` """
return 1.0 * sum(lst)/len(lst)
# now its simple to get the average
for id in points_dict:
print id, avg( points_dict[id] )
A:
I'm not totally sure what you want to do, but I think list filtering would help you. There's built-in function filter, which iterates over a sequence and for each item it calls user-defined function to determine whether to include that item in the resulting list or not.
For instance:
def is4(number):
return number == 4
l = [1, 2, 3, 4, 5, 6, 4, 7, 8, 4, 4]
filter(is4, l) # returns [4, 4, 4, 4]
So, having a list of dictionaries, to filter out all dictionaries with certain entry equal to a given value, you could do something like this:
def filter_dicts(dicts, entry, value):
def filter_function(d):
if entry not in d:
return False
return d[entry] == value
return filter(filter_function, dicts)
With this function, to get all dictionaries with the "id" entry equal to 2, you can do:
result = filter_dicts(your_list, "id", 2)
With this, your main loop could look something like this:
processed_ids = set()
for item in list:
id = item['id']
if id in processed_ids:
continue
processed_ids.add(id)
same_ids = filter_dicts(list, "id", id)
# now do something with same_ids
I hope I understood you correctly and that this is helpful to you.
| loop through list of dictionaries | i have a list of dictionaries. there are several points inside the list, some are multiple. When there is a multiple entry i want to calculate the average of the x and the y of this point. My problem is, that i don't know how to loop through the list of dictionaries to compare the ids of the points!
when i use something like that:
for i in list:
for j in list:
if i['id'] == j['id']:
point = getPoint(i['geom'])
....
sorry, the formating is a little bit tricky... the second loop is inside the first one...
i think it compares the first entry of the list, so it's the same... so i have to start in the second loop with the second entry, but i can't do that with i-1 because i is the hole dictionary...
Someone an idea?
thanks in advance!
for j in range(1, len(NEWPoint)):
if i['gid']==j['gid']:
allsamePoints.append(j)
for k in allsamePoints:
for l in range(1, len(allsamePoints)):
if k['gid']==l['gid']:
Point1 = k['geom']
Point2=l['geom']
X=(Point1.x()+Point2.x())/2
Y=(Point1.y()+Point2.y())/2
AVPoint = QgsPoint(X, Y)
NEWReturnList.append({'gid': j['gid'], 'geom': AVPoint})
del l
for m in NEWReturnList:
for n in range(1, len(NEWReturnList)):
if m['gid']==n['gid']:
Point1 = m['geom']
Point2=n['geom']
X=(Point1.x()+Point2.x())/2
Y=(Point1.y()+Point2.y())/2
AVPoint = QgsPoint(X, Y)
NEWReturnList.append({'gid': j['gid'], 'geom': AVPoint})
del n
else:
pass
ok, i think... at the moment thats more confusing :)...
| [
"One way would be changing the way you store your points, because as you already noticed, it's hard to get what you want out of it. \nA much more useful structure would be a dict where the id maps to a list of points:\nfrom collections import defaultdict\npoints_dict = defaultdict(list)\n\n# make the new dict\nfor ... | [
4,
0
] | [] | [] | [
"dictionary",
"loops",
"python"
] | stackoverflow_0003458285_dictionary_loops_python.txt |
Q:
Viewing Contents Of a DLL File
is this possible to view contents and Functions of a DLL file...
few times ago i was playing with OlyDBG then i found there is option for viewing contents of dll...
so suggest me any good tool or soft for this...
and suppose i have a DLL named "Python27.dll"...
now i need to view the content of this DLL so what do i do...
thanx...
A:
While not trivial to use (you need to understand the format of a Portable Executable, aka PE, file), pefile seems a good, powerful and versatile tool for the purpose of viewing a DLL or any other PE file (I wouldn't risk using it to change such a file, although I see it's one of its features).
For example, excerpting the module's usage examples (and editing to show a dll instead of the equally hypothetical filename they use, which is an exe;-):
import pefile
pe = pefile.PE(‘/path/to/pefile.dll’)
for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols:
print hex(pe.OPTIONAL_HEADER.ImageBase + exp.address), exp.name, exp.ordinal
should, according to the wikipage I pointed to, display something like:
0x7ca0ab4f SHUpdateRecycleBinIcon 336
0x7cab44c0 SHValidateUNC 173
0x7ca7b0aa SheChangeDirA 337
0x7ca7b665 SheChangeDirExA 338
0x7ca7b3e1 SheChangeDirExW 339
0x7ca7aec6 SheChangeDirW 340
0x7ca8baae SheConvertPathW 341
A:
Dependency Walker may provide what you want/need -- it certainly shows all the entry points in a DLL.
A:
On Windows, DUMPBIN provides some DLL inspection capabilities. For example:
DUMPBIN /EXPORTS C:\path\to\my.dll
will display all the exported definitions.
A:
I've done some work with ctypes, and loading dlls in windows, but I don't think DLL have any sort of introspection. This really isn't a big deal, because all of the function calls in DLLs are static. If your trying to use a undocumented DLL, you would not only need to know the names of the functions, but also the parameters of the functions. You would have to reverse engineer the DLL, no small task.
So, in my opinion, I would say no.
| Viewing Contents Of a DLL File | is this possible to view contents and Functions of a DLL file...
few times ago i was playing with OlyDBG then i found there is option for viewing contents of dll...
so suggest me any good tool or soft for this...
and suppose i have a DLL named "Python27.dll"...
now i need to view the content of this DLL so what do i do...
thanx...
| [
"While not trivial to use (you need to understand the format of a Portable Executable, aka PE, file), pefile seems a good, powerful and versatile tool for the purpose of viewing a DLL or any other PE file (I wouldn't risk using it to change such a file, although I see it's one of its features).\nFor example, excerp... | [
5,
3,
1,
0
] | [] | [] | [
"c",
"c#",
"dll",
"import",
"python"
] | stackoverflow_0003454647_c_c#_dll_import_python.txt |
Q:
python code problem
i have this code:
class Check(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
be = "SELECT * FROM Benutzer ORDER BY date "
c = db.GqlQuery(be)
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s is 0:
self.redirect('/')
to check whether the user is registered or not.
but it gives me an error:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/Users/zainab_alhaidary/Desktop/الحمد لله/check.py", line 23, in get
if s is 0:
UnboundLocalError: local variable 's' referenced before assignment
what should i do???
A:
Define s before to assign it a value (also, change the test on s):
user = users.get_current_user()
be = "SELECT * FROM Benutzer ORDER BY date "
c = db.GqlQuery(be)
s=0 # <- init s here
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s == 0: # <- change test on s
self.redirect('/')
A:
Why exactly are you loading all users, then looping through them, just to find one? Use a where clause:
be = "SELECT * FROM Benutzer WHERE benutzer=:1"
c = db.GqlQuery(be, user)
user_from_db = c.get()
if user_from_db is not None: # found someone
dostuff()
else:
self.redirect('/')
A:
You want to set s to 0 before the for loop starts. If the query returns zero items, your for loop doesn't loop even once, so s is undefined.
Also, you should use if s == 0: instead of if s is 0:. In CPython, they are both equivalent, but you shouldn't rely on the fact. See: the documentation for PyInt_FromLong and "is" operator behaves unexpectedly with integers.
A:
You're using 's' before you assign something to it. Add an 's = 0' in the appropriate location.
A:
Your problem is that if c is an empty list then the code in the for loop is never run and s never gets set, hence the error:
UnboundLocalError: local variable 's' referenced before assignment
What the error is telling you that you're referencing - i.e. using - s before it has any value - i.e. before a value has been assigned to it.
To fix this you just ensure s always is assigned a value:
s = 0
for x in c:
if x.benutzer == user:
s = 1
break
else:
s = 2
A:
In the case that c is empty the if statement in the loop never gets executed
you should set s=0 before the for loop
A:
I don't know why you are doing this, but if I understand your code correctly, you have s=1 when x.benutzer == user, and s=2 otherwise (shouldn't this be s=0 if you are going to check against 0?).
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s is 0:
self.redirect('/')
Anyway, here's my solution:
if not any(x.benutzer == user for x in c):
self.redirect('/')
| python code problem | i have this code:
class Check(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
be = "SELECT * FROM Benutzer ORDER BY date "
c = db.GqlQuery(be)
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s is 0:
self.redirect('/')
to check whether the user is registered or not.
but it gives me an error:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/Users/zainab_alhaidary/Desktop/الحمد لله/check.py", line 23, in get
if s is 0:
UnboundLocalError: local variable 's' referenced before assignment
what should i do???
| [
"Define s before to assign it a value (also, change the test on s):\nuser = users.get_current_user()\n\nbe = \"SELECT * FROM Benutzer ORDER BY date \"\n\nc = db.GqlQuery(be)\n\ns=0 # <- init s here\n\nfor x in c:\n if x.benutzer == user:\n s=1\n break\n else:\n s=2\nif s == 0: # <- change test on s... | [
6,
4,
2,
2,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003458950_google_app_engine_python.txt |
Q:
Python 3.X or Python 2.X
What's the ideal Python version for a beginner to start learning Python? I need to recommend some newbies a programming language to learn and I chose Python. I'm still not sure which version.
A:
It depends what you're going to do with it.
Unicode handling has vastly improved in Python 3. So if you intend to use this for building web pages or some such, Python 3 might be the obvious choice.
On the other hand, many libraries and frameworks still only support Python 2. For example, the numerical processing library numpy, and the web framework Django both only work on Python 2. So if you intend to use any of those, stick with Python 2.
Either way, the differences aren't huge to begin with. I'd say Python 3 is a little easier to pick up (due to its string handling), but that is a good reason to learn Python 2 first. That way, if you run into a piece of Python 2 code (and you will), you'll know what is going on.
A:
Adoption of Python3 has been held up by a few critical 3rd party packages. numpy is a good example of a package that has just barely started working on Python3. Quite a few other packages depend on numpy, so they will hopefully be supporting Python3 very shortly too.
Most of the time it's possible to write code that is compatible with 2.6/2.7/3.1 by using __future__ imports. So learning one does not mean you are not learning the other.
A:
My vote is for 3.1
My reasoning is simple and selfish. The more new python programmers that only use 3.1 there are, the more likely it is that one of them is going to decide that they need some library from 2.6 and port it to 3.1 (learning 2.6 in the process I might add).
After this happens, I can start using 3.1: it looks really cool.
A:
I would suggest Python 2.6; I know it's old, but it's not only the current standard, and there is way more documentation and libraries available for it.
A:
I'll throw my experience into the works:
Right now you should be using 2.6. Switch to 2.7 when 2.7.1 comes out. Switch to 3.1/2 when all the libraries you want are fully supported and stable there.
| Python 3.X or Python 2.X | What's the ideal Python version for a beginner to start learning Python? I need to recommend some newbies a programming language to learn and I chose Python. I'm still not sure which version.
| [
"It depends what you're going to do with it.\nUnicode handling has vastly improved in Python 3. So if you intend to use this for building web pages or some such, Python 3 might be the obvious choice.\nOn the other hand, many libraries and frameworks still only support Python 2. For example, the numerical processing... | [
9,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003456088_python.txt |
Q:
Django admin - Edit parent model and related models on the same page
I want to be able to edit all data on one page. How can i achieve this ? Should i modify my models? If so, then how should i modify them?
class TextStyle(models.Model):
color = models.CharField(_("color"), max_length=7)
style = models.CharField(_("style"), max_length=30)
typeface = models.CharField(_("typeface"), max_length=100)
class GenericText(models.Model):
text = models.TextField(_("text"))
lines = models.IntegerField(_("number of lines"))
style = models.ForeignKey(TextStyle, verbose_name=_('text style'), blank=False)
class ExpirationDate(models.Model):
date = models.DateField(_("date"))
style = models.ForeignKey(TextStyle, verbose_name=_('text style'), blank=False)
class Coupon(models.Model):
name = models.CharField(_("name"), max_length=100)
slug = AutoSlugField(populate_from="title")
background = models.ImageField(upload_to="userbackgrounds")
layout = models.ForeignKey(Layout, verbose_name=("layout"), blank=False)
logo = models.ImageField(upload_to="logos")
title = models.OneToOneField(GenericText, verbose_name=("title"), blank=False, related_name="coupon_by_title")
body = models.OneToOneField(GenericText, verbose_name=("body"), blank=False, related_name="coupon_by_body")
disclaimer = models.OneToOneField(GenericText, verbose_name=("disclaimer"), blank=False, related_name="coupon_by_disclaimer")
promo_code = models.OneToOneField(GenericText, verbose_name=("promo code"), blank=False, related_name="coupon_by_promo")
bar_code = models.OneToOneField(BarCode, verbose_name=("barcode"), blank=False, related_name="coupon_by_barcode")
expiration = models.OneToOneField(ExpirationDate, verbose_name=("expiration date"), blank=False, related_name="coupon_by_expiration")
is_template = models.BooleanField( verbose_name=("is a template"), )
category = models.ForeignKey(Category, verbose_name=("category"), blank=True,null=True, related_name="coupons")
user = models.ForeignKey(User, verbose_name=("user"), blank=False)
A:
You need to create an inline model in your admin.py. See: InlineModelAdmin.
A:
I have created a module for inline editting of OneToOne relationships which i called ReverseModelAdmin. You can find it here.
You could use it on your Coupon entity to get all OneToOne relationships inlined like this:
class CouponAdmin(ReverseModelAdmin):
inline_type = 'tabular'
admin.site.register(Coupon, CouponAdmin)
Caveat emptor. I had to hack into lots of internals to make it work, so the solution is brittle and can break easily.
| Django admin - Edit parent model and related models on the same page | I want to be able to edit all data on one page. How can i achieve this ? Should i modify my models? If so, then how should i modify them?
class TextStyle(models.Model):
color = models.CharField(_("color"), max_length=7)
style = models.CharField(_("style"), max_length=30)
typeface = models.CharField(_("typeface"), max_length=100)
class GenericText(models.Model):
text = models.TextField(_("text"))
lines = models.IntegerField(_("number of lines"))
style = models.ForeignKey(TextStyle, verbose_name=_('text style'), blank=False)
class ExpirationDate(models.Model):
date = models.DateField(_("date"))
style = models.ForeignKey(TextStyle, verbose_name=_('text style'), blank=False)
class Coupon(models.Model):
name = models.CharField(_("name"), max_length=100)
slug = AutoSlugField(populate_from="title")
background = models.ImageField(upload_to="userbackgrounds")
layout = models.ForeignKey(Layout, verbose_name=("layout"), blank=False)
logo = models.ImageField(upload_to="logos")
title = models.OneToOneField(GenericText, verbose_name=("title"), blank=False, related_name="coupon_by_title")
body = models.OneToOneField(GenericText, verbose_name=("body"), blank=False, related_name="coupon_by_body")
disclaimer = models.OneToOneField(GenericText, verbose_name=("disclaimer"), blank=False, related_name="coupon_by_disclaimer")
promo_code = models.OneToOneField(GenericText, verbose_name=("promo code"), blank=False, related_name="coupon_by_promo")
bar_code = models.OneToOneField(BarCode, verbose_name=("barcode"), blank=False, related_name="coupon_by_barcode")
expiration = models.OneToOneField(ExpirationDate, verbose_name=("expiration date"), blank=False, related_name="coupon_by_expiration")
is_template = models.BooleanField( verbose_name=("is a template"), )
category = models.ForeignKey(Category, verbose_name=("category"), blank=True,null=True, related_name="coupons")
user = models.ForeignKey(User, verbose_name=("user"), blank=False)
| [
"You need to create an inline model in your admin.py. See: InlineModelAdmin. \n",
"I have created a module for inline editting of OneToOne relationships which i called ReverseModelAdmin. You can find it here. \nYou could use it on your Coupon entity to get all OneToOne relationships inlined like this:\nclass Coup... | [
1,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003129289_django_django_admin_python.txt |
Q:
Django: Is there a way to set global views? For example enable data for a sidebar through all URLS
I am building a Django application that is a pretty basic blog, so far it has been wonderful. I got comments, tags etc up. But one thing is bugging me: I cant get the sidebar i want to work. I use the django.views.generic.date_based generic view and this is my urls.py for the blog:
urlpatterns = patterns('django.views.generic.date_based',
(r'(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail',dict(info_dict, slug_field='slug',template_name='blog/detail.html')),
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, template_name='blog/list.html')),
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/$','archive_day',dict(info_dict,template_name='blog/list.html')),
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month', dict(info_dict, template_name='blog/list.html')),
(r'^(?P<year>\d{4})/$','archive_year', dict(info_dict, template_name='blog/list.html')),
(r'^$','archive_index', dict(info_dict, template_name='blog/list.html')),
)
When i use the URL with 'archive_index' passed i can easily print the latest entries for my sidebar, but when i enter a post i will use one of the top ones where only "object_detail" is availabe. This makes my sidebar entries dissapear. What is the best solution to this problem? Is there a way to make some objects available globally? Through views or otherwise.
A:
People do things like that with template tags. The documentation for custom template tags might be helpful, and there's also a great little tutorial here.
Alternatively, you can use context processors - but that adds an overhead to every single request, which may not be necessary.
| Django: Is there a way to set global views? For example enable data for a sidebar through all URLS | I am building a Django application that is a pretty basic blog, so far it has been wonderful. I got comments, tags etc up. But one thing is bugging me: I cant get the sidebar i want to work. I use the django.views.generic.date_based generic view and this is my urls.py for the blog:
urlpatterns = patterns('django.views.generic.date_based',
(r'(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail',dict(info_dict, slug_field='slug',template_name='blog/detail.html')),
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, template_name='blog/list.html')),
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/$','archive_day',dict(info_dict,template_name='blog/list.html')),
(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month', dict(info_dict, template_name='blog/list.html')),
(r'^(?P<year>\d{4})/$','archive_year', dict(info_dict, template_name='blog/list.html')),
(r'^$','archive_index', dict(info_dict, template_name='blog/list.html')),
)
When i use the URL with 'archive_index' passed i can easily print the latest entries for my sidebar, but when i enter a post i will use one of the top ones where only "object_detail" is availabe. This makes my sidebar entries dissapear. What is the best solution to this problem? Is there a way to make some objects available globally? Through views or otherwise.
| [
"People do things like that with template tags. The documentation for custom template tags might be helpful, and there's also a great little tutorial here.\nAlternatively, you can use context processors - but that adds an overhead to every single request, which may not be necessary.\n"
] | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003459487_django_python.txt |
Q:
What is the best library for reliably dealing with attachments from email?
I have an application and need to write a program that is able to figure out attachments from all kinds of email senders (and MUAs) reliably. PHP doesn't seem to have a great MIME parser so I was hoping some other languages might.
I've seen the PHP Mail Mime Parser but it's not robust at all and I know (and have confirmed) it doesn't work reliably with all MUAs.
Does anyone know of a more real-world-hardened mail parsing library?
I can use any language, doesn't matter.
A:
How about Perl 5's Email::MIME? Looks like something that will fulfill Your needs, if I understood You correctly.
A:
Python's email module is excellent and includes full support for MIME emails, including incremental parsing. I think the moral here is that you can do this in many languages.
Of course, you should do it in Python.
A:
Perl has several email parsing libraries, choose the one which suits your needs best.
A:
I have had a lot of success using Ruby and the mail gem at http://github.com/mikel/mail this is now the default creator/parser for Rails.
I think you are really going to get answers from people with their preference of language so I think its ultimately a question of preference but we use this gem in the web front end of CloudMailin.
| What is the best library for reliably dealing with attachments from email? | I have an application and need to write a program that is able to figure out attachments from all kinds of email senders (and MUAs) reliably. PHP doesn't seem to have a great MIME parser so I was hoping some other languages might.
I've seen the PHP Mail Mime Parser but it's not robust at all and I know (and have confirmed) it doesn't work reliably with all MUAs.
Does anyone know of a more real-world-hardened mail parsing library?
I can use any language, doesn't matter.
| [
"How about Perl 5's Email::MIME? Looks like something that will fulfill Your needs, if I understood You correctly.\n",
"Python's email module is excellent and includes full support for MIME emails, including incremental parsing. I think the moral here is that you can do this in many languages. \nOf course, you sh... | [
4,
3,
3,
0
] | [] | [] | [
"email",
"parsing",
"perl",
"php",
"python"
] | stackoverflow_0003427688_email_parsing_perl_php_python.txt |
Q:
Django: Accessing method on child different child classes through common name
I have an abstract base class for defining common attributes shared by different user profiles.
class Profile(models.Model):
...
def has_permissions(self, project):
...
class Meta:
abstract = True
class Standard(Profile):
...
class Premium(Profile):
...
Now I would like to check the permission of a certain user (having always one distinct profile assigned) without having to know which profile he has, like
user.profile.has_permission(project)
But this does not work because the "Profile" base class is abstract.
Is there a way to circumvent this problem? And is there a way to discover the name of the abstract parent class from a child object?
Thanks,
Daniel
A:
overwrite the auth.User method get_profile() to investigate in all Child-Profile Models Until you find it:
class MyUser(auth.models.User):
profile = models.OneToOneField(Profile)
def get_profile(self):
prof = None
try:
prof = Standard.objects.get(id=self.profile.pk)
except ObjectDoesNotExist:
prof = Premium.objects.get(id=self.profile.pk)
return prof
now, Instead of doing this:
user.profile.has_permission(project)
you can use this:
user.get_profile().has_permission(project)
i hope that it will help you.
A:
I am not entirely convinced that this is the best approach to take. The code is correct in the object sense of things but does not seem to fit the database view (IMHO). User will only have one profile but the database table will have links to multiple Profile tables.
How about:
Make profile at generic relation which can connect to any kind of Profile
Have a single Profile class and define permissions based on instance attribute ('premium' or 'standard')
I am curious to know what others think.
| Django: Accessing method on child different child classes through common name | I have an abstract base class for defining common attributes shared by different user profiles.
class Profile(models.Model):
...
def has_permissions(self, project):
...
class Meta:
abstract = True
class Standard(Profile):
...
class Premium(Profile):
...
Now I would like to check the permission of a certain user (having always one distinct profile assigned) without having to know which profile he has, like
user.profile.has_permission(project)
But this does not work because the "Profile" base class is abstract.
Is there a way to circumvent this problem? And is there a way to discover the name of the abstract parent class from a child object?
Thanks,
Daniel
| [
"overwrite the auth.User method get_profile() to investigate in all Child-Profile Models Until you find it:\n class MyUser(auth.models.User):\n profile = models.OneToOneField(Profile)\n def get_profile(self):\n prof = None\n try:\n prof = Standard.objects.get(id=s... | [
1,
0
] | [] | [] | [
"abstract",
"django",
"inheritance",
"python"
] | stackoverflow_0003457685_abstract_django_inheritance_python.txt |
Q:
How to lock django command for single run. Django. Python
How to lock django commands so it will not run twise in the same time?
A:
Create a lock somewhere - I recently saw very simple lock implementation that used cache:
LOCK_EXPIRE = 60 * 5
lock_id = "%s-lock-%s" % (self.name, id_hexdigest) #computed earlier
is_locked = lambda: str(cache.get(lock_id)) == "true"
acquire_lock = lambda: cache.set(lock_id, "true", LOCK_EXPIRE)
release_lock = lambda: cache.set(lock_id, "nil", 1)
if not is_locked():
aquire_lock()
try:
#do something
finally:
release_lock()
It's just one of many possible implementations.
Edit: Corrected, I just pasted code without thinking. try...finally block is used to ensure that lock is always released, no matter what happens - but of course if statement is also necessary.
A:
There are a bunch of different ways to do this. cji's method looks like it'd work just fine. One thing I tend to do is if my background jobs are operating on model objects, I use status fields to determine if the job can run.
class BookModel(models.Model):
status_choices = ((1, 'new'), ('2', 'processed'))
name = models.CharField(max_length=12)
status = models.CharField(max_length=12, choices=status_choices)
Then if I'm performing something on those books I can do something like so:
if book.status is 1:
## do something
| How to lock django command for single run. Django. Python | How to lock django commands so it will not run twise in the same time?
| [
"Create a lock somewhere - I recently saw very simple lock implementation that used cache:\nLOCK_EXPIRE = 60 * 5\n\nlock_id = \"%s-lock-%s\" % (self.name, id_hexdigest) #computed earlier\n\nis_locked = lambda: str(cache.get(lock_id)) == \"true\"\nacquire_lock = lambda: cache.set(lock_id, \"true\", LOCK_EXPIRE)\nrel... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003459631_django_python.txt |
Q:
Multiple drag and drop in PyQt4
i can't find an example on dragging (and dropping) multiple elements with Qt/PyQt;
In my case i need to drag elements from this QTableView:
class DragTable(QTableView):
def __init__(self, parent = None):
super(DragTable, self).__init__(parent)
self.setDragEnabled(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("application/pubmedrecord"):
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore()
def startDrag(self, event):
print type(event)
index = self.indexAt(event.pos())
if not index.isValid():
return
selected = index.row()
bstream = cPickle.dumps(selected)
mimeData = QMimeData()
mimeData.setData("application/pubmedrecord", bstream)
drag = QDrag(self)
drag.setMimeData(mimeData)
pixmap = QPixmap(":/drag.png")
drag.setHotSpot(QPoint(pixmap.width()/3, pixmap.height()/3))
drag.setPixmap(pixmap)
result = drag.start(Qt.MoveAction)
def mouseMoveEvent(self, event):
self.startDrag(event)
To this QLabel (My dropzone):
class TagLabel(QLabel):
def __init__(self, text, color, parent = None):
super(TagLabel, self).__init__(parent)
self.tagColor = color
self.setText(text)
self.setStyleSheet("QLabel { background-color: %s; font-size: 14pt; }" % self.tagColor)
self.defaultStyle = self.styleSheet()
self.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("application/pubmedrecord"):
self.set_bg(True)
event.accept()
else:
event.reject()
def dragLeaveEvent(self, event):
self.set_bg(False)
event.accept()
def dropEvent(self, event):
self.set_bg(False)
data = event.mimeData()
bstream = data.retrieveData("application/pubmedrecord", QVariant.ByteArray)
selected = pickle.loads(bstream.toByteArray())
event.accept()
self.emit(SIGNAL("dropAccepted(PyQt_PyObject)"), (selected, str(self.text()), str(self.tagColor)))
def set_bg(self, active = False):
if active:
style = "QLabel {background: yellow; font-size: 14pt;}"
self.setStyleSheet(style)
else:
self.setStyleSheet(self.defaultStyle)
Any tips? Thank you!
A:
Here's a full working example:
from PyQt4 import QtCore, QtGui, Qt
import cPickle
import pickle
Why are you using cPickle as well as pickle?
class DragTable(QtGui.QTableView):
def __init__(self, parent = None):
super(DragTable, self).__init__(parent)
self.setDragEnabled(True)
self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
You probably want to set the selection behavior here, because I'm assuming row-based data presentation. You may of course change that.
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("application/pubmedrecord"):
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore()
def startDrag(self, event):
Your code assumes only one index here, based on the event position. For a QTableView, this is unnecessary, as it already handles the mouse click itself. Instead, it's better to depend on Qt to provide you with the information that you actually need, as always. Here, I've chose to use selectedIndexes().
indices = self.selectedIndexes()
Indices is now a list of QModelIndex instances, that I chose to convert to a set of row numbers. It's also possible to convert these to a list of QPersistentModelIndexes, depending on your needs.
One thing that may surprise you here, is that indices contains indexes for all cells in the table, not all rows, regardless of the selection behavior. That's why I chose to use a set instead of a list.
selected = set()
for index in indices:
selected.add(index.row())
I left the rest untouched, assuming that you know what you're doing there.
bstream = cPickle.dumps(selected)
mimeData = QtCore.QMimeData()
mimeData.setData("application/pubmedrecord", bstream)
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
pixmap = QtGui.QPixmap(":/drag.png")
drag.setHotSpot(QtCore.QPoint(pixmap.width()/3, pixmap.height()/3))
drag.setPixmap(pixmap)
result = drag.start(QtCore.Qt.MoveAction)
def mouseMoveEvent(self, event):
self.startDrag(event)
class TagLabel(QtGui.QLabel):
def __init__(self, text, color, parent = None):
super(TagLabel, self).__init__(parent)
self.tagColor = color
self.setText(text)
self.setStyleSheet("QLabel { background-color: %s; font-size: 14pt; }" % self.tagColor)
self.defaultStyle = self.styleSheet()
self.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("application/pubmedrecord"):
self.set_bg(True)
event.accept()
else:
event.reject()
def dragLeaveEvent(self, event):
self.set_bg(False)
event.accept()
def dropEvent(self, event):
self.set_bg(False)
data = event.mimeData()
bstream = data.retrieveData("application/pubmedrecord", QtCore.QVariant.ByteArray)
selected = pickle.loads(bstream.toByteArray())
event.accept()
self.emit(QtCore.SIGNAL("dropAccepted(PyQt_PyObject)"), (selected, str(self.text()), str(self.tagColor)))
Unless you are interfacing with C++-code with this signal, it's not necessary to add a signal argument here, you may also use dropAccepted without parentheses and PyQt4 will do the right thing.
def set_bg(self, active = False):
if active:
style = "QLabel {background: yellow; font-size: 14pt;}"
self.setStyleSheet(style)
else:
self.setStyleSheet(self.defaultStyle)
app = QtGui.QApplication([])
l = TagLabel("bla bla bla bla bla bla bla", "red")
l.show()
m = QtGui.QStandardItemModel()
for _ in xrange(4):
m.appendRow([QtGui.QStandardItem(x) for x in ["aap", "noot", "mies"]])
t = DragTable()
t.setModel(m)
t.show()
def h(o):
print "signal handled", o
l.connect(l, QtCore.SIGNAL("dropAccepted(PyQt_PyObject)"), h)
app.exec_()
| Multiple drag and drop in PyQt4 | i can't find an example on dragging (and dropping) multiple elements with Qt/PyQt;
In my case i need to drag elements from this QTableView:
class DragTable(QTableView):
def __init__(self, parent = None):
super(DragTable, self).__init__(parent)
self.setDragEnabled(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("application/pubmedrecord"):
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore()
def startDrag(self, event):
print type(event)
index = self.indexAt(event.pos())
if not index.isValid():
return
selected = index.row()
bstream = cPickle.dumps(selected)
mimeData = QMimeData()
mimeData.setData("application/pubmedrecord", bstream)
drag = QDrag(self)
drag.setMimeData(mimeData)
pixmap = QPixmap(":/drag.png")
drag.setHotSpot(QPoint(pixmap.width()/3, pixmap.height()/3))
drag.setPixmap(pixmap)
result = drag.start(Qt.MoveAction)
def mouseMoveEvent(self, event):
self.startDrag(event)
To this QLabel (My dropzone):
class TagLabel(QLabel):
def __init__(self, text, color, parent = None):
super(TagLabel, self).__init__(parent)
self.tagColor = color
self.setText(text)
self.setStyleSheet("QLabel { background-color: %s; font-size: 14pt; }" % self.tagColor)
self.defaultStyle = self.styleSheet()
self.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("application/pubmedrecord"):
self.set_bg(True)
event.accept()
else:
event.reject()
def dragLeaveEvent(self, event):
self.set_bg(False)
event.accept()
def dropEvent(self, event):
self.set_bg(False)
data = event.mimeData()
bstream = data.retrieveData("application/pubmedrecord", QVariant.ByteArray)
selected = pickle.loads(bstream.toByteArray())
event.accept()
self.emit(SIGNAL("dropAccepted(PyQt_PyObject)"), (selected, str(self.text()), str(self.tagColor)))
def set_bg(self, active = False):
if active:
style = "QLabel {background: yellow; font-size: 14pt;}"
self.setStyleSheet(style)
else:
self.setStyleSheet(self.defaultStyle)
Any tips? Thank you!
| [
"Here's a full working example:\nfrom PyQt4 import QtCore, QtGui, Qt\nimport cPickle\nimport pickle\n\nWhy are you using cPickle as well as pickle?\nclass DragTable(QtGui.QTableView):\n def __init__(self, parent = None):\n super(DragTable, self).__init__(parent)\n self.setDragEnabled(True)\n ... | [
6
] | [] | [] | [
"drag_and_drop",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0003458542_drag_and_drop_pyqt_pyqt4_python.txt |
Q:
I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines?
I am aware that the standard Python convention for line width is 79 characters. I know lines can be continued in a number of ways, such as automatic string concatenation, parentheses, and the backslash. What does not seem to be as clearly defined is how exactly the overflowing text should be formatted. Do I push it all the way back to col 1? To the col where the original line starts? To the start of the parentheses (if applicable)? For example, say I have something like this:
self.someLongAttributeName = {'someLongKeyName':'someLongValueName',
'anotherLongKeyName':'anotherLongValueName'}
Supposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct?
Now suppose that the first line as shown above is > 79 characters. How should things look in that case?
NOTE: I know that a lot of people disagree with the 79-character convention. While I respect that there are a lot of pros and cons to each side of the issue, this debate is not relevant to my question. I am asking how to follow the convention, not whether or not I should, so please do not espouse the advantages of abandoning it in your reply. Thanks. =)
A:
Supposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct?
Yes, that's how PEP 8 shows it in examples:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if width == 0 and height == 0 and \
color == 'red' and emphasis == 'strong' or \
highlight > 100:
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
But when the opening parenthesis/brace is already close to the 79th column, I usually just exploit this:
Two good reasons to break a particular rule:
(1) When applying the rule would make the code less readable, even for
someone who is used to reading code that follows the rules.
[...]
And do something like
self.some_long_attribute_name = {
'someLongKeyName': 'someLongValueName',
'anotherLongKeyName': 'anotherLongValueName'
}
or
long_object_name.do_something_with_long_name(
long_expression_returning_is_first_arg,
long_expression_returning_is_second_arg
)
A:
http://www.python.org/dev/peps/pep-0008/
See Maximum Line Length
Limit all lines to a maximum of 79
characters.
There are still many devices around
that are limited to 80 character
lines; plus, limiting windows to 80
characters makes it possible to have
several windows side-by-side. The
default wrapping on such devices
disrupts the visual structure of the
code, making it more difficult to
understand. Therefore, please limit
all lines to a maximum of 79
characters. For flowing long blocks
of text (docstrings or comments),
limiting the length to 72 characters
is recommended.
The preferred way of wrapping long
lines is by using Pythons implied line
continuation inside parentheses,
brackets and braces. If necessary,
you can add an extra pair of
parentheses around an expression, but
sometimes using a backslash looks
better. Make sure to indent the
continued line appropriately. The
preferred place to break around a
binary operator is
after the operator, not before it. Some examples:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if width == 0 and height == 0 and \
color == 'red' and emphasis == 'strong' or \
highlight > 100:
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
A:
Even beyond Python, I do this all the time for my C code so I can (as the PEP says) have 2-3 files open on a monitor side-by-side and see them all.
The backslash operator \ works as a line continuation operator in Python as well as C, but I prefer to try to group lines with parenthesis () or braces {} (or brackets [] for Python lists), whatever is most convenient. If I decide I want to add another line in the middle of a long continuing block, I don't want to worry about any stupid 'gotchas': missing a \ or worse, some errant space after the \ invalidating the continuation.
For long conditionals, I like to double-indent so it's more obvious that that code isn't part of the new block.
if (somethingLong == x or
somethingElse == y or
somethingOld == z or
x < y < z or
doIt.now()):
pass
A:
In PEP 8 there is an example:
class Rectangle(Blob):
def __init__(self, width, height,
# more code
Blob.__init__(self, width, height,
color, emphasis, highlight)
Which, to my eye, suggests that your example is correct. I think you should break first line of the example after opening bracket ( { ) like so:
self.someLongAttributeName = {
'someLongKeyName':'someLongValueName',
'anotherLongKeyName':'anotherLongValueName'
}
if it is too long. I don't know if it is 'pythonic', but should be familiar and readable.
A:
The preferred way of wrapping long
lines is by using Python's implied
line
continuation inside parentheses, brackets and braces. If necessary,
you
can add an extra pair of parentheses around an expression, but
sometimes
using a backslash looks better. Make sure to indent the continued line
appropriately. The preferred place to break around a binary
operator is
after the operator, not before it.
A:
I was pretty sure this was answered here before, but I can't find it now so..
The short answer is that PEP8 does not cover how to format object literals, other than that colons should have zero spaces before and one space after.
I do them like this:
obj = {
'foo': 1,
'bar': 2,
'bas': 3,
}
A:
Good trick is also to do like this:
my_long_string="""
This are
many lines of text
"""
a = [a in my_long_string.split() if a]
Some people prefer to use \ after opening triple quote and not filter empty lines, but I really hate those beasts.
For your particular example I agree with cji.
| I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines? | I am aware that the standard Python convention for line width is 79 characters. I know lines can be continued in a number of ways, such as automatic string concatenation, parentheses, and the backslash. What does not seem to be as clearly defined is how exactly the overflowing text should be formatted. Do I push it all the way back to col 1? To the col where the original line starts? To the start of the parentheses (if applicable)? For example, say I have something like this:
self.someLongAttributeName = {'someLongKeyName':'someLongValueName',
'anotherLongKeyName':'anotherLongValueName'}
Supposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct?
Now suppose that the first line as shown above is > 79 characters. How should things look in that case?
NOTE: I know that a lot of people disagree with the 79-character convention. While I respect that there are a lot of pros and cons to each side of the issue, this debate is not relevant to my question. I am asking how to follow the convention, not whether or not I should, so please do not espouse the advantages of abandoning it in your reply. Thanks. =)
| [
"\nSupposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct?\n\nYes, that's how PEP 8 shows it in examples:\nclass Rectangle(Blob):\n\n def __init__(self, width, height,\n color='black', emphasis=None, highlight=0):\n if width =... | [
11,
5,
3,
2,
1,
0,
0
] | [] | [] | [
"code_formatting",
"conventions",
"python"
] | stackoverflow_0003459423_code_formatting_conventions_python.txt |
Q:
Is it possible to make Python functions behave like instances?
I understand that functions can have attributes. So I can do the following:
def myfunc():
myfunc.attribute += 1
print(myfunc.attribute)
myfunc.attribute = 1
Is it possible by any means to make such a function behave as if it were an instance? For example, I'd like to be able to do something like this:
x = clever_wrapper(myfunc)
y = clever_wrapper(myfunc)
x.attribute = 5
y.attribute = 9
x() # I want this to print 6 (from the 5 plus increment)
y() # I want this to print 10 (from the 9 plus increment)
As it stands, there is only one "instance" of the function, so attribute only exists once. Modifying it by either x or y changes the same value. I'd like each of them to have their own attribute. Is that possible to do at all? If so, can you provide a simple, functional example?
It is important that I be able to access attribute from inside of the function but have the value of attribute be different depending on which "instance" of the function is called. Essentially, I'd like to use attribute as if it were another parameter to the function (so that it could change the behavior of the function) but not pass it in. (Suppose that the signature of the function were fixed so that I cannot change the parameter list.) But I need to be able to set the different values for attribute and then call the functions in sequence. I hope that makes sense.
The main answers seem to be saying to do something like this:
class wrapper(object):
def __init__(self, target):
self.target = target
def __call__(self, *args, **kwargs):
return self.target(*args, **kwargs)
def test(a):
return a + test.attribute
x = wrapper(test)
y = wrapper(test)
x.attribute = 2
y.attribute = 3
print(x.attribute)
print(y.attribute)
print(x(3))
print(y(7))
But that doesn't work. Maybe I've done it incorrectly, but it says that test does not have attribute. (I'm assuming that it's because wrapper actually has the attribute.)
The reason I need this is because I have a library that expects a function with a particular signature. It's possible to put those functions into a pipeline of sorts so that they're called in order. I'd like to pass it multiple versions of the same function but change their behavior based on an attribute's value. So I'd like to be able to add x and y to the pipeline, as opposed to having to implement a test1 function and a test2 function that both do almost exactly the same thing (except for the value of the attribute).
A:
You can make a class with a __call__ method which would achieve a similar thing.
Edit for clarity: Instead of making myfunc a function, make it a callable class. It walks like a function and it quacks like a function, but it can have members like a class.
A:
A nicer way:
def funfactory( attribute ):
def func( *args, **kwargs ):
# stuff
print( attribute )
# more stuff
return func
x = funfactory( 1 )
y = funfactory( 2 )
x( ) # 1
y( ) # 2
This works because the functions are closures, so they will grab all local variables in their scope; this causes a copy of attribute to be passed around with the function.
A:
class Callable(object):
def __init__(self, x):
self.x = x
def __call__(self):
self.x += 1
print self.x
>> c1 = Callable(5)
>> c2 = Callable(20)
>> c1()
6
>> c1()
7
>> c2()
21
>> c2()
22
A:
#!/usr/bin/env python
# encoding: utf-8
class Callable(object):
attribute = 0
def __call__(self, *args, **kwargs):
return self.attribute
def main():
c = Callable()
c.attribute += 1
print c()
if __name__ == '__main__':
main()
A:
A generator might be an alternate solution here:
def incgen(init):
while True:
init += 1
print init
yield
x = incgen(5)
y = incgen(9)
x.next() # prints 6
y.next() # prints 10
y.next() # prints 11
x.next() # prints 7
You can't dig back in to the generator and manipulate the data though.
| Is it possible to make Python functions behave like instances? | I understand that functions can have attributes. So I can do the following:
def myfunc():
myfunc.attribute += 1
print(myfunc.attribute)
myfunc.attribute = 1
Is it possible by any means to make such a function behave as if it were an instance? For example, I'd like to be able to do something like this:
x = clever_wrapper(myfunc)
y = clever_wrapper(myfunc)
x.attribute = 5
y.attribute = 9
x() # I want this to print 6 (from the 5 plus increment)
y() # I want this to print 10 (from the 9 plus increment)
As it stands, there is only one "instance" of the function, so attribute only exists once. Modifying it by either x or y changes the same value. I'd like each of them to have their own attribute. Is that possible to do at all? If so, can you provide a simple, functional example?
It is important that I be able to access attribute from inside of the function but have the value of attribute be different depending on which "instance" of the function is called. Essentially, I'd like to use attribute as if it were another parameter to the function (so that it could change the behavior of the function) but not pass it in. (Suppose that the signature of the function were fixed so that I cannot change the parameter list.) But I need to be able to set the different values for attribute and then call the functions in sequence. I hope that makes sense.
The main answers seem to be saying to do something like this:
class wrapper(object):
def __init__(self, target):
self.target = target
def __call__(self, *args, **kwargs):
return self.target(*args, **kwargs)
def test(a):
return a + test.attribute
x = wrapper(test)
y = wrapper(test)
x.attribute = 2
y.attribute = 3
print(x.attribute)
print(y.attribute)
print(x(3))
print(y(7))
But that doesn't work. Maybe I've done it incorrectly, but it says that test does not have attribute. (I'm assuming that it's because wrapper actually has the attribute.)
The reason I need this is because I have a library that expects a function with a particular signature. It's possible to put those functions into a pipeline of sorts so that they're called in order. I'd like to pass it multiple versions of the same function but change their behavior based on an attribute's value. So I'd like to be able to add x and y to the pipeline, as opposed to having to implement a test1 function and a test2 function that both do almost exactly the same thing (except for the value of the attribute).
| [
"You can make a class with a __call__ method which would achieve a similar thing.\nEdit for clarity: Instead of making myfunc a function, make it a callable class. It walks like a function and it quacks like a function, but it can have members like a class.\n",
"A nicer way:\ndef funfactory( attribute ):\n def... | [
7,
2,
1,
0,
0
] | [] | [] | [
"attributes",
"function",
"python"
] | stackoverflow_0003459758_attributes_function_python.txt |
Q:
Converting (part of) a numpy recarray into a 2d array?
We've got a set of recarrays of data for individual days - the first attribute is a timestamp and the rest are values.
Several of these:
ts a b c
2010-08-06 08:00, 1.2, 3.4, 5.6
2010-08-06 08:05, 1.2, 3.4, 5.6
2010-08-06 08:10, 1.2, 3.4, 5.6
2010-08-06 08:15, 2.2, 3.3, 5.6
2010-08-06 08:20, 1.2, 3.4, 5.6
We'd like to produce an array of the averages of each of the values (as if you laid all of the day data on top of each other, and averaged all of the values that line up). The timestamp times all match up, so we can do it by creating a result recarray with the timestamps, and the other columns all 0s, then doing something like:
for day in day_data:
result.a += day.a
result.b += day.b
result.c += day.c
result.a /= len(day_data)
result.b /= len(day_data)
result.c /= len(day_data)
It seems like a better way would be to convert each day to a 2d array with just the numbers (lopping off the timestamps), then average them all element-wise in one operation, but we can't find a way to do this - it's always a 1d array of objects.
Does anyone know how to do this?
A:
There are several ways to do this. One way is to select multiple columns of the recarray and cast them as floats, then reshape back into a 2D array:
new_data = data[['a','b','c']].astype(np.float).reshape((data.size, 3))
Alternatively, you might consider something like this (negligibly slower, but more readable):
new_data = np.vstack([data[item] for item in ['a','b','c']]).T
Also note that it might be a good idea to look into pandas for operations such as these so that you can easily work with heterogeneous data.
| Converting (part of) a numpy recarray into a 2d array? | We've got a set of recarrays of data for individual days - the first attribute is a timestamp and the rest are values.
Several of these:
ts a b c
2010-08-06 08:00, 1.2, 3.4, 5.6
2010-08-06 08:05, 1.2, 3.4, 5.6
2010-08-06 08:10, 1.2, 3.4, 5.6
2010-08-06 08:15, 2.2, 3.3, 5.6
2010-08-06 08:20, 1.2, 3.4, 5.6
We'd like to produce an array of the averages of each of the values (as if you laid all of the day data on top of each other, and averaged all of the values that line up). The timestamp times all match up, so we can do it by creating a result recarray with the timestamps, and the other columns all 0s, then doing something like:
for day in day_data:
result.a += day.a
result.b += day.b
result.c += day.c
result.a /= len(day_data)
result.b /= len(day_data)
result.c /= len(day_data)
It seems like a better way would be to convert each day to a 2d array with just the numbers (lopping off the timestamps), then average them all element-wise in one operation, but we can't find a way to do this - it's always a 1d array of objects.
Does anyone know how to do this?
| [
"There are several ways to do this. One way is to select multiple columns of the recarray and cast them as floats, then reshape back into a 2D array:\nnew_data = data[['a','b','c']].astype(np.float).reshape((data.size, 3))\n\nAlternatively, you might consider something like this (negligibly slower, but more readab... | [
8
] | [] | [] | [
"numpy",
"python",
"recarray"
] | stackoverflow_0003459611_numpy_python_recarray.txt |
Q:
Python + and * operators
I'm working my way through some code examples and I stumbled upon this:
endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th']
+ ['st']
I understand that for numbers after 4 and until 20 they end in 'th' and I can see that we are adding 17 more items to the list, and I understand that '17 * ['th'] is adding 'th' to the list 17 times, however, I don't understand how this works.
Can you shed some light on this?
A:
17 * ['th'] generates ['th', 'th', ..., 'th'] (17 items).
In addition it's worth noting 2 behaviours:
That this is only really useful because the contents 'th' is immutable (unless of course you never intended to modify the ending list).
The list object ['th'] is only created once, however it is extended by iterating over the original copy 17 times, appending each entry to the final ['th', ...] list. This in turn is merged with the surrounding endings via the + operator.
I don't normally shed my light. Only about once every 6 months. If you see it lying about don't tell anyone it's mine.
A:
The + operator returns the 'sum' of 2 list, or both of them concatenated together. The * operator returns a list added to itself X times.
http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch14s03.html
A:
When multiplying a list, you're creating a new list containing the elements of the list that many times. In this case, 17 * ['th'] creates a list containing seventeen strings 'th'. When adding lists together, you're creating a new list containing the elements of all operands.
>>> a = [1, 2]
>>> a * 2
[1, 2, 1, 2]
>>> a = ['th']
>>> b = ['st']
>>> 3 * a + b
['th', 'th', 'th', 'st']
A:
The part of the code 17 * ['th'] creates a list with 17 items that are all 'th' and the + operator concatenates the list together, so ['st', 'nd', 'rd'] + 17 * ['th'] would become ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th']
A:
That makes the following list:
endings = [ "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th" ]
So if you want to write "21st", do
"{0}{1}".format( 21, endings[ 20 ] )
Notice that the list is off by one, since endings[0] is the first element.
A:
Consider
twentieth
twenty first
twenty second
twenty third
...
thirtieth
thirty first
Or is it something else that you don't understand about it?
A:
Additionally, you can override the operators of your own objects e.g.
#!/usr/bin/env python
# encoding: utf-8
class SomeClass(object):
def __init__(self, v):
self.value = v
def __add__(self, b):
return self.value + b.value
def main():
a = SomeClass(1)
b = SomeClass(2)
print a + b
if __name__ == '__main__':
main()
see http://docs.python.org/library/operator.html for more details
| Python + and * operators | I'm working my way through some code examples and I stumbled upon this:
endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th']
+ ['st']
I understand that for numbers after 4 and until 20 they end in 'th' and I can see that we are adding 17 more items to the list, and I understand that '17 * ['th'] is adding 'th' to the list 17 times, however, I don't understand how this works.
Can you shed some light on this?
| [
"17 * ['th'] generates ['th', 'th', ..., 'th'] (17 items).\nIn addition it's worth noting 2 behaviours:\n\nThat this is only really useful because the contents 'th' is immutable (unless of course you never intended to modify the ending list).\nThe list object ['th'] is only created once, however it is extended by i... | [
5,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0003460162_operators_python.txt |
Q:
Is there a good language/syntax for field validation we can re-use?
I'm working on a web app (using Python & Bottle) and building a decorator for validating HTTP parameters sent in GET or POST. The early version takes callables, so this:
@params(user_id=int, user_name=unicode)
... ensures that user_id is an int, user_name is a string, and both fields exist.
But that's not enough. I want to be able to specify that user_name is optional, or that it must be non-empty and within 40 characters. Implementing that is easy enough, but I'm struggling with what syntax would be most elegant. It seems like that might be a problem someone's solved before, but I'm not finding an answer. Specifically I'm wondering if there's an elegant way to take parseable strings that provide the syntax. Something like:
@params(user_id='int:min1', user_name='unicode:required:max40')
I just don't want to invent a syntax if there's a good one floating around somewhere.
Anyone seen something like this? In any language..but I'm specifically valuing terseness and readability.
A:
You could use lists.
@validate(user_id=[int, min(1)], user_name=[unicode,required,max(40)])
And each item could be a function (or class/object) that gets executed with the corresponding field as an argument. If it raises an error, it fails validation.
| Is there a good language/syntax for field validation we can re-use? | I'm working on a web app (using Python & Bottle) and building a decorator for validating HTTP parameters sent in GET or POST. The early version takes callables, so this:
@params(user_id=int, user_name=unicode)
... ensures that user_id is an int, user_name is a string, and both fields exist.
But that's not enough. I want to be able to specify that user_name is optional, or that it must be non-empty and within 40 characters. Implementing that is easy enough, but I'm struggling with what syntax would be most elegant. It seems like that might be a problem someone's solved before, but I'm not finding an answer. Specifically I'm wondering if there's an elegant way to take parseable strings that provide the syntax. Something like:
@params(user_id='int:min1', user_name='unicode:required:max40')
I just don't want to invent a syntax if there's a good one floating around somewhere.
Anyone seen something like this? In any language..but I'm specifically valuing terseness and readability.
| [
"You could use lists.\n@validate(user_id=[int, min(1)], user_name=[unicode,required,max(40)])\n\nAnd each item could be a function (or class/object) that gets executed with the corresponding field as an argument. If it raises an error, it fails validation.\n"
] | [
2
] | [] | [] | [
"forms",
"html",
"http",
"python",
"validation"
] | stackoverflow_0003460398_forms_html_http_python_validation.txt |
Q:
Storing data for web application in python dictionary
Is it feasible to store data for a web application inside the program itself, e.g. as a large dictionary? The data would mostly be just a few hundred short-ish text blocks (roughly blog post size), and it will not be altered/added to at all by the users (although I would want to be able to update it myself every so often).
Up until now I've been looking at standard database storage solutions, but since (for this set of objects at least) they will not be modified, is it possible simply to store them as a dictionary? Or are there serious downsides I have not considered?
Thanks.
A:
It is certainly possible. The amount of data you can store will be limited mostly by memory available.
If you are planning to perform database-like operations on the data then you are better off with an in-memory database like SQLite. If the data is picked up from a database and hashed then you might want to use Memcached. If you are limiting yourself to plain text and the data won't grow then you can stick to memory.
The approach will start losing its charm if the data will grow in the future. In that case you are better off with other solutions.
| Storing data for web application in python dictionary | Is it feasible to store data for a web application inside the program itself, e.g. as a large dictionary? The data would mostly be just a few hundred short-ish text blocks (roughly blog post size), and it will not be altered/added to at all by the users (although I would want to be able to update it myself every so often).
Up until now I've been looking at standard database storage solutions, but since (for this set of objects at least) they will not be modified, is it possible simply to store them as a dictionary? Or are there serious downsides I have not considered?
Thanks.
| [
"It is certainly possible. The amount of data you can store will be limited mostly by memory available.\nIf you are planning to perform database-like operations on the data then you are better off with an in-memory database like SQLite. If the data is picked up from a database and hashed then you might want to use ... | [
2
] | [] | [] | [
"database",
"python",
"sql",
"web_applications"
] | stackoverflow_0003460853_database_python_sql_web_applications.txt |
Q:
Plotting in a loop (with basemap and pyplot)....problems with pyplot.clf()
I am plotting some weather data for a research project. The plot consists of 18 timesteps. I decided the best way to accomplish this was to make a new plot for each timestep, save it a file, and create a new plot for the next timestep (using a for loop).
For example:
map_init #[Basemap Instance]
extra_shapes #[Basemap.readshapefile object]
for i in range(timesteps):
#plot the weather data for current timestep to current plot
map_init.imshow(data[i])
# extra_shapes are county boundaries. Plot those as polygons
pyplot.Polygon(map_init.extra_shapes[i])
# Plot the state boundaries (in basemap)
map_init.drawstates()
# add a colorbar
pyplot.colorbar()
# Save the figure
pyplot.savefig(filepath)
#close figure and loop again (if necessary)
pyplot.clf()
The problem lies with pyplot.clf()
The code works except for one thing. Only the first plot comes out as expected. Every subsequent plot is missing the extra_shapes (ie no county boundaries). I do not understand the relation between presence of pyplot.clf() and the failure of pyplot.Polygon() ?
If removed, extra_shapes is plotted, but then every plot has multiple colorbars (depending on the value of i). The only reason pyplot.clf() is there is to avoid having 18 colorbars in the final plot. Is there a way to force one and only one colorbar per plot?
A:
Try making a new figure instead of using clf().
e.g.
for i in range(timesteps):
fig = pyplot.figure()
...
fig.savefig(filepath)
Alternatively (and faster) you could just update the data in your image object
(returned by imshow()).
e.g. something like (completely untested):
map_init #[Basemap Instance]
extra_shapes #[Basemap.readshapefile object]
#plot the weather data for current timestep to current plot
img = map_init.imshow(data[0])
# extra_shapes are county boundaries. Plot those as polygons
plygn = pyplot.Polygon(map_init.extra_shapes[0])
# Plot the state boundaries (in basemap)
map_init.drawstates()
# add a colorbar
pyplot.colorbar()
for i in range(timestamps):
img.set_data(data[i])
plygn.set_xy(map_init.extra_shapes[i])
pyplot.draw()
pyplot.savefig(filepath)
However, there's a chance that that method might not play well with basemap. I may also be misremembering the correct way to redraw the figure, but I'm fairly sure it's just plt.draw()...
Hope that helps a bit anyway
Edit: Just noticed that you're drawing your polygons inside of a loop, as well. Updated the second example to properly reflect that.
| Plotting in a loop (with basemap and pyplot)....problems with pyplot.clf() | I am plotting some weather data for a research project. The plot consists of 18 timesteps. I decided the best way to accomplish this was to make a new plot for each timestep, save it a file, and create a new plot for the next timestep (using a for loop).
For example:
map_init #[Basemap Instance]
extra_shapes #[Basemap.readshapefile object]
for i in range(timesteps):
#plot the weather data for current timestep to current plot
map_init.imshow(data[i])
# extra_shapes are county boundaries. Plot those as polygons
pyplot.Polygon(map_init.extra_shapes[i])
# Plot the state boundaries (in basemap)
map_init.drawstates()
# add a colorbar
pyplot.colorbar()
# Save the figure
pyplot.savefig(filepath)
#close figure and loop again (if necessary)
pyplot.clf()
The problem lies with pyplot.clf()
The code works except for one thing. Only the first plot comes out as expected. Every subsequent plot is missing the extra_shapes (ie no county boundaries). I do not understand the relation between presence of pyplot.clf() and the failure of pyplot.Polygon() ?
If removed, extra_shapes is plotted, but then every plot has multiple colorbars (depending on the value of i). The only reason pyplot.clf() is there is to avoid having 18 colorbars in the final plot. Is there a way to force one and only one colorbar per plot?
| [
"Try making a new figure instead of using clf().\ne.g.\nfor i in range(timesteps):\n fig = pyplot.figure()\n ...\n fig.savefig(filepath)\n\nAlternatively (and faster) you could just update the data in your image object\n(returned by imshow()).\ne.g. something like (completely untested):\nmap_init #[Basema... | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003460707_matplotlib_python.txt |
Q:
Python: File works on the command line but not with crontab
So I have a file that looks like so:
#!/usr/bin/python
import MySQLdb
import subprocess
from subprocess import call
import re
conx = MySQLdb.connect (user = 'root', passwd = '******', db = 'vaxijen_antigens')
cursor = conx.cursor()
cursor.execute('select * from sequence')
row = cursor.fetchall()
f = open('/home/rv/ncbi-blast-2.2.23+/db/vdatabase.fasta', 'w')
for i in row:
f.write('>'+i[0].strip()+'\n')
s = re.sub(r'[^\w]','',str(i[1]))
s = ''.join(s)
for k in range(0, len(s), 60):
f.write('%s\n' % (s[k:k+60]))
f.write('\n')
f.close()
subprocess.call(['formatdb', '-p', 'T', '-i', r'/home/rv/ncbi-blast-2.2.23+/db/vdatabase.fasta'])
The file runs no problem from the command line but when I try and run it with crontab I get this error:
File "/home/rv/ncbi-blast-2.2.23+/db/formatdb.py", line 29, in <module>
subprocess.call(['formatdb', '-p', 'T', '-i',
r'/home/rv/ncbi-blast-2.2.23+/db/vdatabase.fasta'])
OSError: [Errno 2] No such file or directory
I don't understand, the file exist in that directory, I've double and triple checked. I tried converting the file path to a raw string hence the lower case "r" before the path but that didn't do it either.
A:
I suspect it's complaining about the path to "formatdb" in your subprocess call. Try changing that to the full path:
subprocess.call(['/home/path/formatdb', ...])
A:
The cron daemon usually provides only a very limited PATH. Either put a more complete PATH in the crontab or use the full pathname in the Python code.
| Python: File works on the command line but not with crontab | So I have a file that looks like so:
#!/usr/bin/python
import MySQLdb
import subprocess
from subprocess import call
import re
conx = MySQLdb.connect (user = 'root', passwd = '******', db = 'vaxijen_antigens')
cursor = conx.cursor()
cursor.execute('select * from sequence')
row = cursor.fetchall()
f = open('/home/rv/ncbi-blast-2.2.23+/db/vdatabase.fasta', 'w')
for i in row:
f.write('>'+i[0].strip()+'\n')
s = re.sub(r'[^\w]','',str(i[1]))
s = ''.join(s)
for k in range(0, len(s), 60):
f.write('%s\n' % (s[k:k+60]))
f.write('\n')
f.close()
subprocess.call(['formatdb', '-p', 'T', '-i', r'/home/rv/ncbi-blast-2.2.23+/db/vdatabase.fasta'])
The file runs no problem from the command line but when I try and run it with crontab I get this error:
File "/home/rv/ncbi-blast-2.2.23+/db/formatdb.py", line 29, in <module>
subprocess.call(['formatdb', '-p', 'T', '-i',
r'/home/rv/ncbi-blast-2.2.23+/db/vdatabase.fasta'])
OSError: [Errno 2] No such file or directory
I don't understand, the file exist in that directory, I've double and triple checked. I tried converting the file path to a raw string hence the lower case "r" before the path but that didn't do it either.
| [
"I suspect it's complaining about the path to \"formatdb\" in your subprocess call. Try changing that to the full path:\nsubprocess.call(['/home/path/formatdb', ...])\n\n",
"The cron daemon usually provides only a very limited PATH. Either put a more complete PATH in the crontab or use the full pathname in the P... | [
5,
3
] | [] | [] | [
"crontab",
"python"
] | stackoverflow_0003460867_crontab_python.txt |
Q:
Format date like: Monday, 1st March
Seems like it should be simple enough but it's driving me up the wall. I've looked at the python date formatting strings and it still doesn't make too much sense.
Here's what I'm trying to do: <Full day>, <Day of month><Ordinal> <Month>
Where <Ordinal> is st, nd, rd, th, etc depending on the day.
A:
Update 2: Looks like OP found this useful after all :)
Update: Never mind. The OP was looking for Django date formatting, not Python.
AFAIK there is no built in format specifier for the ordinal. The others are easy:
my_date.strftime('%A, %d %B')
I found this solution on the web:
if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
A:
Just found the answer in the docs. God knows why they're not linked to from every reference to date formatting.
{{e.when|date:"l, jS F"}}
Outside of templates:
from django.utils import dateformat
dateformat.format(datetime.now(), 'l, jS F')
| Format date like: Monday, 1st March | Seems like it should be simple enough but it's driving me up the wall. I've looked at the python date formatting strings and it still doesn't make too much sense.
Here's what I'm trying to do: <Full day>, <Day of month><Ordinal> <Month>
Where <Ordinal> is st, nd, rd, th, etc depending on the day.
| [
"Update 2: Looks like OP found this useful after all :)\nUpdate: Never mind. The OP was looking for Django date formatting, not Python.\nAFAIK there is no built in format specifier for the ordinal. The others are easy:\nmy_date.strftime('%A, %d %B')\n\nI found this solution on the web:\nif 4 <= day <= 20 or 24 <= d... | [
5,
4
] | [] | [] | [
"date",
"date_formatting",
"django",
"python"
] | stackoverflow_0003460962_date_date_formatting_django_python.txt |
Q:
Get global variables from file as dict?
I've got a file, constants.py, that contains a bunch of global constants. Is there a way I can grab all of them as dict, for just this file?
A:
It should be simple:
import constants
print(constants.__dict__)
A:
import constants
constants_dict = {}
for constant in dir(constants):
constants_dict[constant] = getattr(constants, constant)
I'm not sure I see the point of this though. How is writing constants_dict['MY_CONSTANT'] any better/easier/more readable than constants.MY_CONSTANT?
EDIT:
Based on the comments, I see some potential uses now.
Here's another way to write the above, depending on how compact you want it.
constants_dict = dict((c, getattr(constants, c)) for c in dir(constants))
EDIT2:
cji for the win! constants.__dict__
| Get global variables from file as dict? | I've got a file, constants.py, that contains a bunch of global constants. Is there a way I can grab all of them as dict, for just this file?
| [
"It should be simple:\nimport constants\nprint(constants.__dict__)\n\n",
"import constants\n\nconstants_dict = {}\nfor constant in dir(constants):\n constants_dict[constant] = getattr(constants, constant)\n\nI'm not sure I see the point of this though. How is writing constants_dict['MY_CONSTANT'] any better/e... | [
5,
2
] | [] | [] | [
"global",
"import",
"python"
] | stackoverflow_0003460864_global_import_python.txt |
Q:
Indexer with two keys in python
I'm newbie with python. I want to write a class with two keys as indexer. also need to be able to use them inside of class like this:
a = Cartesian(-10,-10,10,10) # Cartesian is the name of my class
a[-5][-1]=10
and in the Cartesian class:
def fill(self,value):
self[x][y] = x*y-value
I try with
def __getitem__(self,x,y):
return self.data[x-self.dx][y-self.dy]
but doesn't work.
A:
If you just need a lightweight application, you can have __getitem__ accept a tuple:
def __getitem__(self, c):
x, y = c
return self.data[x-self.dx][y-self.dy]
def __setitem__(self, c, v):
x, y = c
self.data[x-self.dx][y-self.dy] = v
and use like this:
a[-5,-1] = 10
However, if you are doing a lot of numeric computation or this is integral to your application, consider using Numpy and just represent this coordinate as a vector: http://numpy.scipy.org/
A:
Is there any reason you actually need to explicitly define a Cartesian() class? For example, are there calculation methods on it? If not, then just use a lists within lists to use this type of syntax.
If you do need a class, then consider adding a .coordinate(x, y) method to it instead and don't bother trying to do the list syntax.
A:
Accept a tuple:
>>> class Foo(object):
... def __getitem__(self, key):
... x, y = key
... print x, y
... f = Foo()
... f[1,2]
1 2
| Indexer with two keys in python | I'm newbie with python. I want to write a class with two keys as indexer. also need to be able to use them inside of class like this:
a = Cartesian(-10,-10,10,10) # Cartesian is the name of my class
a[-5][-1]=10
and in the Cartesian class:
def fill(self,value):
self[x][y] = x*y-value
I try with
def __getitem__(self,x,y):
return self.data[x-self.dx][y-self.dy]
but doesn't work.
| [
"If you just need a lightweight application, you can have __getitem__ accept a tuple:\ndef __getitem__(self, c):\n x, y = c\n return self.data[x-self.dx][y-self.dy]\n\ndef __setitem__(self, c, v):\n x, y = c\n self.data[x-self.dx][y-self.dy] = v\n\nand use like this:\na[-5,-1] = 10\n\nHowever, if you are doing ... | [
14,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003461167_python.txt |
Q:
Printing output from classes other than main class with python?
In order to keep my code clean and organized, I split my classes up into a bunch of different files and folders, here is what a typical project structure will look like for me:
> Project
__init__.py
main.py
ui.py
> lib
foo.py
bar.py
In my ui.py file, I usually define some sort of info function if the application is just a command line application. That usually looks something like this:
def info(message, level=1):
if level == 1:
token = "[+] "
elif level == 2:
token = "\t[-] "
print token + str(message)
Now the question is, if I am doing a lot of the work in main.py, and have therefore created a ui object in it by importing it in, what is the best way then to use the same info function in foo.py or bar.py?
A:
import project.ui or from project import ui should do the trick. Don't tell anyone I told you about the second option. The parent directory of project needs to be on your python path.
| Printing output from classes other than main class with python? | In order to keep my code clean and organized, I split my classes up into a bunch of different files and folders, here is what a typical project structure will look like for me:
> Project
__init__.py
main.py
ui.py
> lib
foo.py
bar.py
In my ui.py file, I usually define some sort of info function if the application is just a command line application. That usually looks something like this:
def info(message, level=1):
if level == 1:
token = "[+] "
elif level == 2:
token = "\t[-] "
print token + str(message)
Now the question is, if I am doing a lot of the work in main.py, and have therefore created a ui object in it by importing it in, what is the best way then to use the same info function in foo.py or bar.py?
| [
"import project.ui or from project import ui should do the trick. Don't tell anyone I told you about the second option. The parent directory of project needs to be on your python path.\n"
] | [
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003461223_oop_python.txt |
Q:
Parse this date in Python: 5th November 2010
I'm having a bad time with date parsing and formatting today.
Points for somebody who can parse this date format into a datetime.date or datetime.datetime (I'm not too fussy but I'd prefer .date):
5th November 2010
A:
Using dateutil:
In [2]: import dateutil.parser as dparser
In [3]: date = dparser.parse('5th November 2010')
In [4]: date
Out[4]: datetime.datetime(2010, 11, 5, 0, 0)
A:
Unfortunately, strptime has no format characters for "skip an ordinal suffix" -- so, I'd do the skipping first, with a little RE, and then parse the resulting "clear" string. I.e.:
>>> import re
>>> import datetime
>>> ordn = re.compile(r'(?<=\d)(st|nd|rd|th)\b')
>>> def parse(s):
... cleans = ordn.sub('', s)
... dt = datetime.datetime.strptime(cleans, '%d %B %Y')
... return dt.date()
...
>>> parse('5th November 2010')
datetime.date(2010, 11, 5)
Your preference for date vs datetime is no problem of course, that's what the .date() method of datetime objects is for;-).
Third-party extensions like dateutil can be useful if you need to do a lot of "fuzzy" date parsing (or other fancy date-related stuff;-), by the way.
A:
If the ordinal is constant then:
datetime.strptime(s, '%dth %B %Y')
Else:
date_str = '5th November 2010'
modified_date_str = date_str[0:1] + date_str[3:]
datetime.strptime(modified_date_str, '%d %B %Y')
Or like ~unutbu said use dateutil :)
| Parse this date in Python: 5th November 2010 | I'm having a bad time with date parsing and formatting today.
Points for somebody who can parse this date format into a datetime.date or datetime.datetime (I'm not too fussy but I'd prefer .date):
5th November 2010
| [
"Using dateutil:\nIn [2]: import dateutil.parser as dparser\n\nIn [3]: date = dparser.parse('5th November 2010')\n\nIn [4]: date\nOut[4]: datetime.datetime(2010, 11, 5, 0, 0)\n\n",
"Unfortunately, strptime has no format characters for \"skip an ordinal suffix\" -- so, I'd do the skipping first, with a little RE, ... | [
17,
10,
5
] | [] | [] | [
"date_formatting",
"python",
"python_datetime"
] | stackoverflow_0003461435_date_formatting_python_python_datetime.txt |
Q:
Django Url Not Resolving with Query Parameters
I have an issue where I need to pass in query parameters for a GET request, but Django is not resolving the URL correctly to the view.
My urls.py looks like this:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^confirm_cancel',
'myapp.views.confirm_cancel_method',
name='myapp_confirm_cancel'),
)
When I goto /confirm_cancel?some_id=x I get a 404, telling me "No MyModel matches query." When I set a breakpoint in my view handler, it does not get hit when I goto that url.
However, if I goto /confirm_cancel/x/, my view breakpoint does get hit.
One more thing to note, this worked in Django 1.1, but is now broken since I upgraded to 1.2.
Any thoughts?
Thanks!
A:
I don't think the problem is with your url. Are you using a shortcut like get_object_or_4o4 somewhere in your view? For example:
get_object_or_404(MyModel, pk=99)
would result in a "No MyModel matches given query, if there wasn't a record in your table with a primary key of 99.
A:
We need to see what's in the corresponding view function.
Ideally, it should look something like this:
def confirm_cancel_method(request, some_id=None):
some_id = request.REQUEST.get('some_id', some_id)
some_record = get_object_or_404(SomeModel, pk=some_id)
...
update
Sorry, just saw your note about the breakpoint. One thing I'd recommend is changing the config to this:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^confirm_cancel/?$',
'myapp.views.confirm_cancel_method',
name='myapp_confirm_cancel'),
)
Adding /?$ at the end means that only /confirm_cancel or /confirm_cancel/ will match the url. Right now because you don't have the ending $ anything starting with confirm_cancel will match. Fixing the pattern will at least resolve this issue.
A:
I had copied out all the other url patterns in the urls.py in my post.
Turns out that the issue was that I had a r'^(?P<my_id>\w+)/?$' for one of the urls at the top of the urlpatterns.
Next time I'll learn to paste everything instead of cherry picking what I think are the offending lines of code.
Strange that this did not cause Django 1.1 to break... I guess it was a bug that was fixed in 1.2
A:
Did you check if this was a case of the trailing slash?
| Django Url Not Resolving with Query Parameters | I have an issue where I need to pass in query parameters for a GET request, but Django is not resolving the URL correctly to the view.
My urls.py looks like this:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^confirm_cancel',
'myapp.views.confirm_cancel_method',
name='myapp_confirm_cancel'),
)
When I goto /confirm_cancel?some_id=x I get a 404, telling me "No MyModel matches query." When I set a breakpoint in my view handler, it does not get hit when I goto that url.
However, if I goto /confirm_cancel/x/, my view breakpoint does get hit.
One more thing to note, this worked in Django 1.1, but is now broken since I upgraded to 1.2.
Any thoughts?
Thanks!
| [
"I don't think the problem is with your url. Are you using a shortcut like get_object_or_4o4 somewhere in your view? For example:\nget_object_or_404(MyModel, pk=99)\n\nwould result in a \"No MyModel matches given query, if there wasn't a record in your table with a primary key of 99.\n",
"We need to see what's ... | [
1,
1,
1,
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003460910_django_django_urls_python.txt |
Q:
Problem using replaceWith to replace HTML tags with BeautifulSoup on Python
I am using BeautifulSoup in Python and am having trouble replacing some tags. I am finding <div> tags and checking for children. If those children do not have children (are a text node of NODE_TYPE = 3), I am copying them to be a <p>.
from BeautifulSoup import Tag, BeautifulSoup
class bar:
self.soup = BeautifulSoup(self.input)
foo()
def foo(self):
elements = soup.findAll(True)
for node in elements:
# ....other stuff here if not <div> tags.
if node.name.lower() == "div":
if not node.find('a'):
newTag = Tag(self.soup, "p")
newTag.setString(node.text)
node.replaceWith(newTag)
nodesToScore.append(newTag)
else:
for n in node.findAll(True):
if n.getString(): # False if has children
newTag = Tag(self.soup, "p")
newTag.setString(n.text)
n.replaceWith(newTag)
I'm getting an AttributeError:
File "file.py", line 125, in function
node.replaceWith(newTag)
File "BeautifulSoup.py", line 131, in replaceWith
myIndex = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'
I do the same replacing on node higher up in the for loop and it works correctly. I'm assuming it's having problems because of the additional iterating through node as n.
What am I doing wrong or what would be a better way to do this? Thanks!
PS. I'm using Python 2.5 for Google Appengine and BeautifulSoup 3.0.8.1
A:
The error says:
myIndex = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'
This code occurs on line 131 of BeautifulSoup.py.
It says that self.parent is None.
Looking at the surrounding code shows that self should equal node in your code, since node is calling its replaceWith method.(Note: The error message says node.replaceWith, but the code you posted shows n.replaceWith. The code you posted does not correspond to the error message/traceback.) So apparently node.parent is None.
You could probably avoid the error by placing
if node.parent is not None:
at some point in the code before node.replaceWith is called.
Edit: I suggest you use print statements to investigate where in the HTML you are when node.parent is None (i.e. where the error is occurring). Maybe use print node.contents or print node.previous.contents or print node.next.contents to see where you are. Once you see the HTML it might become obvious what pathological situation you are in which is causing node.parent to be None.
| Problem using replaceWith to replace HTML tags with BeautifulSoup on Python | I am using BeautifulSoup in Python and am having trouble replacing some tags. I am finding <div> tags and checking for children. If those children do not have children (are a text node of NODE_TYPE = 3), I am copying them to be a <p>.
from BeautifulSoup import Tag, BeautifulSoup
class bar:
self.soup = BeautifulSoup(self.input)
foo()
def foo(self):
elements = soup.findAll(True)
for node in elements:
# ....other stuff here if not <div> tags.
if node.name.lower() == "div":
if not node.find('a'):
newTag = Tag(self.soup, "p")
newTag.setString(node.text)
node.replaceWith(newTag)
nodesToScore.append(newTag)
else:
for n in node.findAll(True):
if n.getString(): # False if has children
newTag = Tag(self.soup, "p")
newTag.setString(n.text)
n.replaceWith(newTag)
I'm getting an AttributeError:
File "file.py", line 125, in function
node.replaceWith(newTag)
File "BeautifulSoup.py", line 131, in replaceWith
myIndex = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'
I do the same replacing on node higher up in the for loop and it works correctly. I'm assuming it's having problems because of the additional iterating through node as n.
What am I doing wrong or what would be a better way to do this? Thanks!
PS. I'm using Python 2.5 for Google Appengine and BeautifulSoup 3.0.8.1
| [
"The error says:\n myIndex = self.parent.index(self)\nAttributeError: 'NoneType' object has no attribute 'index'\n\nThis code occurs on line 131 of BeautifulSoup.py.\nIt says that self.parent is None.\nLooking at the surrounding code shows that self should equal node in your code, since node is calling its repla... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003461814_beautifulsoup_python.txt |
Q:
Django, subdomains and mod_rewrite. URLs messing up on deployment setups
I have a Django application being served of (say) example.com. It contains a number of sub-applications (say) strength, speed and skill. The URL scheme is something like http://example.com/strength, http://example.com/speed and http://example.com/skill. This is how I run my dev server (using runserver) and there are no problems whatsoever.
Now, during deployment, I need to have subdomains that map to these sub-applications. More specifically, I want http://x.example.com to map to http://example.com/x (for the above values of x) and then processing can go on.
I googled a little bit and found two ways of doing this.
One is to get some middleware to get the subdomain part of the URL and keep it inside the request object passed to my view methods. I then do the whole thing inside my application logic.
The other is to use Apache mod_rewrite to do the above URL translation and then let my app run as usual.
I chose the latter since it looked neater and I thought I wouldn't have to include deployment specific code inside my core application.
Now, I'm bitten by a problem which I can't really find a way out of. Inside the skill application, I have a named url skill_home. It's http://example.com/skill. However, once I deploy, the skill_home URL becomes http://skill.example.com/skill. Django appends the /skill to the top level domain and this is what I get. If I do a GET on this URL, mod_rewrite changes it to http://skill.example.com/skill/skill and it doesn't work.
My mod_rewrite snippets look like this
RewriteCond %{HTTP_HOST} !www.example.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?skill.example.com [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) /skill/$1
How do I fix this neatly?
A:
For this answer I'm assuming that you're willing to do a mod_rewrite for each subdomain. I don't think this will work for any subdomain (i.e. the x you mention).
This will strip out the leading /skill/ so that your app will continue to work:
RewriteCond %{HTTP_HOST} !www.example.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?skill.example.com [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (/skill/)?(.*) /skill/$2
Update
Okay, so you want to strip out the leading part of the URL in the link itself.
Basically, that means you have to write a custom tag to replace the {% url %} tag, something like this:
import re
from django.template import Library
from django.template.defaulttags import URLNode, url
register = Library()
class SubdomainURLNode(URLNode):
def render(self, context):
domain = context['request'].get_host()
subdomain = re.sub(r'^www\.','',domain).split('.')[0]
path = super(SubdomainURLNode, self).render(context)
return re.sub(r'^/%s/' % subdomain, '/', path)
@register.tag
def subdomainurl(parser, token, node_cls=SubdomainURLNode):
"""Just like {% url %} but checks for a subdomain."""
node_instance = url(parser, token)
return node_cls(view_name=node_instance.view_name,
args=node_instance.args,
kwargs=node_instance.kwargs,
asvar=node_instance.asvar)
I've tested this on my server and it appears to work.
| Django, subdomains and mod_rewrite. URLs messing up on deployment setups | I have a Django application being served of (say) example.com. It contains a number of sub-applications (say) strength, speed and skill. The URL scheme is something like http://example.com/strength, http://example.com/speed and http://example.com/skill. This is how I run my dev server (using runserver) and there are no problems whatsoever.
Now, during deployment, I need to have subdomains that map to these sub-applications. More specifically, I want http://x.example.com to map to http://example.com/x (for the above values of x) and then processing can go on.
I googled a little bit and found two ways of doing this.
One is to get some middleware to get the subdomain part of the URL and keep it inside the request object passed to my view methods. I then do the whole thing inside my application logic.
The other is to use Apache mod_rewrite to do the above URL translation and then let my app run as usual.
I chose the latter since it looked neater and I thought I wouldn't have to include deployment specific code inside my core application.
Now, I'm bitten by a problem which I can't really find a way out of. Inside the skill application, I have a named url skill_home. It's http://example.com/skill. However, once I deploy, the skill_home URL becomes http://skill.example.com/skill. Django appends the /skill to the top level domain and this is what I get. If I do a GET on this URL, mod_rewrite changes it to http://skill.example.com/skill/skill and it doesn't work.
My mod_rewrite snippets look like this
RewriteCond %{HTTP_HOST} !www.example.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?skill.example.com [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) /skill/$1
How do I fix this neatly?
| [
"For this answer I'm assuming that you're willing to do a mod_rewrite for each subdomain. I don't think this will work for any subdomain (i.e. the x you mention).\nThis will strip out the leading /skill/ so that your app will continue to work:\nRewriteCond %{HTTP_HOST} !www.example.com$ [NC]\nRewriteCond %{HTTP_HOS... | [
3
] | [] | [] | [
"django",
"mod_rewrite",
"python",
"subdomain"
] | stackoverflow_0003461806_django_mod_rewrite_python_subdomain.txt |
Q:
Multithreaded Python script taking longer than non-threaded script
Disclaimer: I'm pretty terrible with multithreading, so it's entirely possible I'm doing something wrong.
I've written a very basic raytracer in Python, and I was looking for ways to possibly speed it up. Multithreading seemed like an option, so I decided to try it out. However, while the original script took ~85 seconds to process my sample scene, the multithreaded script ends up taking ~125 seconds, which seems pretty unintuitive.
Here's what the original looks like (I'm not going to copy the drawing logic and stuff in here. If someone thinks that would be needed to figure out the problem, I'll go ahead and put it back in):
def getPixelColor(x, y, scene):
<some raytracing code>
def draw(outputFile, scene):
<some file handling code>
for y in range(scene.getHeight()):
for x in range(scene.getWidth()):
pixelColor = getPixelColor(x, y, scene)
<write pixelColor to image file>
if __name__ == "__main__":
scene = readScene()
draw(scene)
And here's the multithreaded version:
import threading
import Queue
q = Queue.Queue()
pixelDict = dict()
class DrawThread(threading.Thread):
def __init__(self, scene):
self.scene = scene
threading.Thread.__init__(self)
def run(self):
while True:
try:
n, x, y = q.get_nowait()
except Queue.Empty:
break
pixelDict[n] = getPixelColor(x, y, self.scene)
q.task_done()
def getPixelColor(x, y, scene):
<some raytracing code>
def draw(outputFile, scene):
<some file handling code>
n = 0
work_threads = 4
for y in range(scene.getHeight()):
for x in range(scene.getWidth()):
q.put_nowait((n, x, y))
n += 1
for i in range(work_threads):
t = DrawThread(scene)
t.start()
q.join()
for i in range(n)
pixelColor = pixelDict[i]
<write pixelColor to image file>
if __name__ == "__main__":
scene = readScene()
draw(scene)
Is there something obvious that I'm doing wrong? Or am I incorrect in assuming that multithreading would give a speed boost to a process like this?
A:
I suspect the Python Global Interpreter Lock is preventing your code from running in two threads at once.
What is a global interpreter lock (GIL)?
Clearly you want to take advantage of multiple CPUs. Can you split the ray tracing across processes instead of threads?
The multithreaded version obviously does more "work" so I would expect it to be slower on a single CPU.
I also dislike subclassing Thread, and just construct a new thread with t = Thread(target=myfunc); t.run()
A:
To directly answer your question, Python threading will not improve the performance and the GIL may actually make it worse.
In the larger scheme of things, I love python and ray tracing, but you should never combine them. A Python ray tracer would be at least 2 orders of magnitude slower than a C or even C++ version of the same.
So while your question is interesting from a Python programmers point of view, it is rather funny from a ray tracing point of view.
A:
I suspect you may have one of two problems (or both really). First, I agree with Joe that the Global Interpreter Lock is likely causing problems.
Second, it looks like you write a file a lot during this process (particularly in the non-threaded version when you do it every iteration of the inner loop). Is it possible that you were time-bound on the disk not CPU? If so, then when you added the threading you added overhead to manage the threads without resolving the actual bottleneck. When optimizing make sure you identify you bottlenecks first, so you can at least guess about which are likely to give you the most bang for your buck when addressing them.
| Multithreaded Python script taking longer than non-threaded script | Disclaimer: I'm pretty terrible with multithreading, so it's entirely possible I'm doing something wrong.
I've written a very basic raytracer in Python, and I was looking for ways to possibly speed it up. Multithreading seemed like an option, so I decided to try it out. However, while the original script took ~85 seconds to process my sample scene, the multithreaded script ends up taking ~125 seconds, which seems pretty unintuitive.
Here's what the original looks like (I'm not going to copy the drawing logic and stuff in here. If someone thinks that would be needed to figure out the problem, I'll go ahead and put it back in):
def getPixelColor(x, y, scene):
<some raytracing code>
def draw(outputFile, scene):
<some file handling code>
for y in range(scene.getHeight()):
for x in range(scene.getWidth()):
pixelColor = getPixelColor(x, y, scene)
<write pixelColor to image file>
if __name__ == "__main__":
scene = readScene()
draw(scene)
And here's the multithreaded version:
import threading
import Queue
q = Queue.Queue()
pixelDict = dict()
class DrawThread(threading.Thread):
def __init__(self, scene):
self.scene = scene
threading.Thread.__init__(self)
def run(self):
while True:
try:
n, x, y = q.get_nowait()
except Queue.Empty:
break
pixelDict[n] = getPixelColor(x, y, self.scene)
q.task_done()
def getPixelColor(x, y, scene):
<some raytracing code>
def draw(outputFile, scene):
<some file handling code>
n = 0
work_threads = 4
for y in range(scene.getHeight()):
for x in range(scene.getWidth()):
q.put_nowait((n, x, y))
n += 1
for i in range(work_threads):
t = DrawThread(scene)
t.start()
q.join()
for i in range(n)
pixelColor = pixelDict[i]
<write pixelColor to image file>
if __name__ == "__main__":
scene = readScene()
draw(scene)
Is there something obvious that I'm doing wrong? Or am I incorrect in assuming that multithreading would give a speed boost to a process like this?
| [
"I suspect the Python Global Interpreter Lock is preventing your code from running in two threads at once.\nWhat is a global interpreter lock (GIL)?\nClearly you want to take advantage of multiple CPUs. Can you split the ray tracing across processes instead of threads?\nThe multithreaded version obviously does more... | [
8,
2,
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003461899_multithreading_python.txt |
Q:
Python subprocess problem
I'm writing a script to generate a CSR in Python. The script is very simple. I generate an RSA private key by using the following:
keycmd = "openssl genrsa -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdout=PIPE)
csrcmd = "openssl req -new -key mykey.pem -subj "+ subj + " -out mycsr.csr"
reqprocess = Popen(csrcmd, shell=True, stdout=PIPE)
However, I want to add the functionality to encrypt the private key with a password is the user desires. This is normally done by including the option "-des3" in the genrsa command, but I don't know how to pipe a string from Python standard input to the OpenSSL process. Any help would be appreciated.
What I want to do is:
keycmd = "openssl genrsa -des3 -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdin=PIPE, stdout=PIPE)
keyprocess.communicate("password")
keyprocess.communicate("password")
It's not working however, the script just freezes and never gets past the first communicate statement.
A:
Add the option -passout stdin to the openssl genrsa command, and it will read the passphrase from standard input. That should allow you to send it in via communicate.
There are several other values you can provide to the -passout option to obtain the passphrase from another source. See the OpenSSL man page for details.
A:
Have you tried the Pexpect module ?
import pexpect
child = pexpect.spawn(keycmd)
child.expect("Enter pass phrase")
child.sendline("password")
child.expect("Verifying - Enter pass phrase")
child.sendline("password")
| Python subprocess problem | I'm writing a script to generate a CSR in Python. The script is very simple. I generate an RSA private key by using the following:
keycmd = "openssl genrsa -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdout=PIPE)
csrcmd = "openssl req -new -key mykey.pem -subj "+ subj + " -out mycsr.csr"
reqprocess = Popen(csrcmd, shell=True, stdout=PIPE)
However, I want to add the functionality to encrypt the private key with a password is the user desires. This is normally done by including the option "-des3" in the genrsa command, but I don't know how to pipe a string from Python standard input to the OpenSSL process. Any help would be appreciated.
What I want to do is:
keycmd = "openssl genrsa -des3 -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdin=PIPE, stdout=PIPE)
keyprocess.communicate("password")
keyprocess.communicate("password")
It's not working however, the script just freezes and never gets past the first communicate statement.
| [
"Add the option -passout stdin to the openssl genrsa command, and it will read the passphrase from standard input. That should allow you to send it in via communicate.\nThere are several other values you can provide to the -passout option to obtain the passphrase from another source. See the OpenSSL man page for de... | [
3,
2
] | [] | [] | [
"csr",
"openssl",
"pipe",
"python"
] | stackoverflow_0003460971_csr_openssl_pipe_python.txt |
Q:
Python Object Oriented Design; Return, Set Instance Variable Or Both
Ok I have some code that boils down to a pattern like this
class Foo(object):
def get_something1(self):
# in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
self.something1 = "foo_something1"
def get_something2(self):
# needs the result of get_something1; right now I have it get it by instance variable like so
self.something2 = self.something1 + "_something_2"
My question is, should I do the above (methods getting what they need by instance variables) or by taking arguments like so; also should I return something1 and something2 in the get_* methods?
class Foo(object):
def get_something1(self):
# in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
self.something1 = "foo_something1"
def get_something2(self, something_1):
# needs the result of get_something1; right now I have it get it by instance variable like so
self.something2 = something1 + "_something_2"
Now in my code the methods return deferreds (twisted); Right now when the deferreds fire it sets the instance variables and returns None; In the actual code I have another function that checks to see if something1 or something2 is expired; I update them which brings up a problem because I update it like so...
d = self.get_something1()
##d.addCallback(self.get_something2) # errors because it gets the argument None (so I do below)
d.addCallback(lambda ignored: self.get_something2())# problem the deferred for get_something2 is inaccessible
So right now the update code is either ugly, error filled, or both. So I have a feeling that I am doing something either a) un pythonic or b) un twisted or c) some other bad design.
Thanks for the answers, but those won't work because the functions return deferreds and not the actual value (other wise it would have to block).
A:
Don't use get_* methods. In Python the better way is to use properties:
class Foo(object):
@property
def something1(self):
# in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
return "foo_something1"
@property
def something2(self):
# needs the result of get_something1; right now I have it get it by instance variable like so
return self.something1 + "_something_2"
Note that when something1 is a property, self.something1 (without parentheses!) calls the corresponding function Foo.something1.
Once you have working code, you can see how something2 is being used. If you have both
@property
def something2(self):
return self.something1 + "_something_2"
@property
def something3(self):
return self.otherthing1 + "_something_2"
Then you might want to refactor the code to use
def something2(self,prefix):
return prefix+"_something_2"
We don't know enough about your situation to tell you which is better. But the answer may become obvious to you once you see the use patterns of your working code.
| Python Object Oriented Design; Return, Set Instance Variable Or Both | Ok I have some code that boils down to a pattern like this
class Foo(object):
def get_something1(self):
# in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
self.something1 = "foo_something1"
def get_something2(self):
# needs the result of get_something1; right now I have it get it by instance variable like so
self.something2 = self.something1 + "_something_2"
My question is, should I do the above (methods getting what they need by instance variables) or by taking arguments like so; also should I return something1 and something2 in the get_* methods?
class Foo(object):
def get_something1(self):
# in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
self.something1 = "foo_something1"
def get_something2(self, something_1):
# needs the result of get_something1; right now I have it get it by instance variable like so
self.something2 = something1 + "_something_2"
Now in my code the methods return deferreds (twisted); Right now when the deferreds fire it sets the instance variables and returns None; In the actual code I have another function that checks to see if something1 or something2 is expired; I update them which brings up a problem because I update it like so...
d = self.get_something1()
##d.addCallback(self.get_something2) # errors because it gets the argument None (so I do below)
d.addCallback(lambda ignored: self.get_something2())# problem the deferred for get_something2 is inaccessible
So right now the update code is either ugly, error filled, or both. So I have a feeling that I am doing something either a) un pythonic or b) un twisted or c) some other bad design.
Thanks for the answers, but those won't work because the functions return deferreds and not the actual value (other wise it would have to block).
| [
"Don't use get_* methods. In Python the better way is to use properties:\nclass Foo(object):\n @property\n def something1(self):\n # in the actual code it asks a web server but here I replaced that with \"foo_something1\" instead of the code from a web server\n return \"foo_something1\"\n @pr... | [
4
] | [] | [] | [
"object",
"oop",
"python"
] | stackoverflow_0003462645_object_oop_python.txt |
Q:
In Python, how do I check that a file is a text file?
The file is uploaded through a Django form. The contents of the file need to be saved into a models.TextField(), for editors to review it before publication.
I am already checking UploadedFile.content_type. I have considered using a regular input field, but as the text is going to be quite long, it would be unwieldy for users to cut and paste.
A:
Google is your friend on this one - see here
A:
Not all sequences of bytes are valid for ex. UTF-8, maybe you should check this?
| In Python, how do I check that a file is a text file? | The file is uploaded through a Django form. The contents of the file need to be saved into a models.TextField(), for editors to review it before publication.
I am already checking UploadedFile.content_type. I have considered using a regular input field, but as the text is going to be quite long, it would be unwieldy for users to cut and paste.
| [
"Google is your friend on this one - see here\n",
"Not all sequences of bytes are valid for ex. UTF-8, maybe you should check this?\n"
] | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003462951_django_python.txt |
Q:
site.addsitedir not fully processing .pth file
This is a apache/mod_wsgi/virtualenv/django stack. In the virtualenv site-packages dir I've got a virtualenv_path_extensions.pth file. The apache conf has a
WSGIScriptAlias / /path/to/my.wsgi
my.wsgi has
site.addsitedir('/path/to/virtualenv/site-packages')
Now, if I start up a python shell, import site, and call the line above, my sys.path looks correct : it has loaded all the paths in the virtualenv_path_extensions.pth
However, Under apache I'm getting 500 errors because it claims django is not on the path. When I log sys.path after the addsitedir line in my.wsgi, it looks as if it has added the first line of virtualenv_path_extensions.pth, but not the rest!
What might cause that?
A:
Ah, selinux :D
The paths that were not getting loaded had the wrong context, and apache wasn't able to touch them ...
** must remember to check those selinux logs when mysteries arise **
| site.addsitedir not fully processing .pth file | This is a apache/mod_wsgi/virtualenv/django stack. In the virtualenv site-packages dir I've got a virtualenv_path_extensions.pth file. The apache conf has a
WSGIScriptAlias / /path/to/my.wsgi
my.wsgi has
site.addsitedir('/path/to/virtualenv/site-packages')
Now, if I start up a python shell, import site, and call the line above, my sys.path looks correct : it has loaded all the paths in the virtualenv_path_extensions.pth
However, Under apache I'm getting 500 errors because it claims django is not on the path. When I log sys.path after the addsitedir line in my.wsgi, it looks as if it has added the first line of virtualenv_path_extensions.pth, but not the rest!
What might cause that?
| [
"Ah, selinux :D\nThe paths that were not getting loaded had the wrong context, and apache wasn't able to touch them ...\n** must remember to check those selinux logs when mysteries arise **\n"
] | [
1
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"virtualenv"
] | stackoverflow_0003460585_apache_mod_wsgi_python_virtualenv.txt |
Q:
Why is a success message considered an error in ftplib
import ftplib
server = '192.168.1.109'
user = 'bob'
password = 'likes_sandwiches'
box = ftplib.FTP(server)
box.login(user, password)
s = box.mkd('\\a\\this4\\')
box.close()
x = raw_input('done, eat sandwiches now')
This returns:
Traceback (most recent call last):
File "C:\scripts\ftp_test.py", line 25, in
s = box.mkd('\E\this4\')
File "C:\Python26\lib\ftplib.py", line 553, in mkd
return parse257(resp)
File "C:\Python26\lib\ftplib.py", line 651, in parse257
raise error_reply, resp
error_reply: 250 Directory created successfully.
It successfully created a directory, but it thinks its an error! WTF?
I plan on creating many directories in a loop, how can I do this without having it break every time it successfully creates a single directory?
A:
According to RFC 959 (FTP), the only valid response code to MKD is 257. Looks like this is a problem caused by the FTP server not conforming to the standard.
For your interest, this is the relevant ftplib code:
if resp[:3] != '257':
raise error_reply, resp
A:
ftplib is expecting a result of 257, defined as " created", so it can parse the <pathname> and return it for you; but your server is surprisingly giving a result of 250 and does not return the pathname, so the mkd method of course fails.
As a workaround to this peculiar server behavior, you can use voidcmd to just send the MKD /your/path command -- after all, you know the pathname you want to create, since it's an absolute one.
| Why is a success message considered an error in ftplib | import ftplib
server = '192.168.1.109'
user = 'bob'
password = 'likes_sandwiches'
box = ftplib.FTP(server)
box.login(user, password)
s = box.mkd('\\a\\this4\\')
box.close()
x = raw_input('done, eat sandwiches now')
This returns:
Traceback (most recent call last):
File "C:\scripts\ftp_test.py", line 25, in
s = box.mkd('\E\this4\')
File "C:\Python26\lib\ftplib.py", line 553, in mkd
return parse257(resp)
File "C:\Python26\lib\ftplib.py", line 651, in parse257
raise error_reply, resp
error_reply: 250 Directory created successfully.
It successfully created a directory, but it thinks its an error! WTF?
I plan on creating many directories in a loop, how can I do this without having it break every time it successfully creates a single directory?
| [
"According to RFC 959 (FTP), the only valid response code to MKD is 257. Looks like this is a problem caused by the FTP server not conforming to the standard.\nFor your interest, this is the relevant ftplib code:\nif resp[:3] != '257':\n raise error_reply, resp\n\n",
"ftplib is expecting a result of 257, defin... | [
1,
1
] | [] | [] | [
"ftp",
"ftplib",
"python"
] | stackoverflow_0003463033_ftp_ftplib_python.txt |
Q:
Python App Engine import issues after app is cached
I'm using a modified version on juno (http://github.com/breily/juno/) in Google App Engine. The problem I'm having is I have code like this:
import juno
import pprint
@get('/')
def home(web):
pprint.pprint("test")
def main():
run()
if __name__ == '__main__':
main()
The first time I start the app up in the dev environment it works fine. The second time and every time after that it can't find pprint. I get this error:
AttributeError: 'NoneType' object has no attribute 'pprint'
If I set the import inside the function it works every time:
@get('/')
def home(web):
import pprint
pprint.pprint("test")
So it seems like it is caching the function but for some reason the imports are not being included when it uses that cache. I tried removing the main() function at the bottom to see if that would remove the caching of this script but I get the same problem.
Earlier tonight this code was working fine, I'm not sure what could have changed to cause this. Any insight is appreciated.
A:
Is it possible you are reassigning the name pprint somewhere? The only two ways I know of for a module-level name (like what you get from the import statement) to become None is if you either assign it yourself pprint = None or upon interpreter shutdown, when Python's cleanup assigns all module-level names to None as it shuts things down.
A:
I would leave it that way. I saw a slideshare that Google put out about App Engine optimization that said you can get better performance by keeping imports inside of the methods, so they are not imported unless necessary.
| Python App Engine import issues after app is cached | I'm using a modified version on juno (http://github.com/breily/juno/) in Google App Engine. The problem I'm having is I have code like this:
import juno
import pprint
@get('/')
def home(web):
pprint.pprint("test")
def main():
run()
if __name__ == '__main__':
main()
The first time I start the app up in the dev environment it works fine. The second time and every time after that it can't find pprint. I get this error:
AttributeError: 'NoneType' object has no attribute 'pprint'
If I set the import inside the function it works every time:
@get('/')
def home(web):
import pprint
pprint.pprint("test")
So it seems like it is caching the function but for some reason the imports are not being included when it uses that cache. I tried removing the main() function at the bottom to see if that would remove the caching of this script but I get the same problem.
Earlier tonight this code was working fine, I'm not sure what could have changed to cause this. Any insight is appreciated.
| [
"Is it possible you are reassigning the name pprint somewhere? The only two ways I know of for a module-level name (like what you get from the import statement) to become None is if you either assign it yourself pprint = None or upon interpreter shutdown, when Python's cleanup assigns all module-level names to Non... | [
0,
0
] | [] | [] | [
"caching",
"google_app_engine",
"import",
"python"
] | stackoverflow_0001895744_caching_google_app_engine_import_python.txt |
Q:
Reading and comparing lines in a file using Python
I have a file of the following format.
15/07/2010 14:14:13 changed_status_from_Offline_to_Available
15/07/2010 15:01:09 changed_status_from_Available_to_Offline
15/07/2010 15:15:35 changed_status_from_Offline_to_Away became_idle
15/07/2010 15:16:29 changed_status_from_Away_to_Available became_unidle
15/07/2010 15:45:40 changed_status_from_Available_to_Away became_idle
15/07/2010 16:05:40 changed_status_from_Away_to_Available became_unidle
15/07/2010 16:51:39 changed_status_from_Available_to_Offline
20/07/2010 13:07:26 changed_status_from_Offline_to_Available
I need to create a function in python that has to arguments: date and time. It should read the file and return the second status if the date matches and time is less than the time in the function call. That is
Lets say i call the function returnstatus(15/07/2010, 15:10:01).
The function should go to the file and return the status of the user on that day at that time, which in this case is "Offline".
I am a Python newbie and any help would be really appreciated.
A:
import datetime
import time
def lines( path_to_file ):
'''Open path_to_file and read the lines one at a time, yielding tuples
( date of line, time of line, status before line )'''
with open( path_to_file ) as theFile:
for line in theFile:
line = line.rsplit( " ", 1 )
yield (
datetime.datetime.strptime( line[ 0 ], "%d/%m/%Y %H:%M:%S" ),
line[ 1 ].split( "_" )[ 3 ]
)
def return_status( statDate ):
for lineDate, lineStatus in lines( path_to_file ):
if statDate > lineDate:
continue
return lineStatus
Does that make sense, or would you like me to explain any of it?
Edit
Did you mean what you said above?
date matches and time is less than the time in the function call
In other words, what should happen if you call return_status( 16/07/2010, <some.time> )? Should you get "Offline"?
Another Edit
I have edited it to do sensible datetime comparisons. I think you have read the inequality the wrong way around: we loop through lines in the file until the first line after the date we wish to fetch (keep reading while statDate > lineDate). Once this test fails, line is the first line after the desired date, so its from value is the status at the time we requested. You should call the function with a datetime.datetime.
A:
I suggest you have a read in the python docs, specifically the time module and the function strptime which can parse textual representation of times into a programmatic representation.
Calling returnstatus the way you wrote in the question will surely fail, you might want to call it with a string representation of the time (i.e. "15/07/2010 15:10:01") or by passing one of the datatypes defined in the time module.
EDIT: obviously if you pass in a string time then finding it in the file is much easier:
if substring in line:
# do stuff
A:
As Yoni said, you're probably better served by passing a string argument (if you have one). You may also find the types in datetime useful. You'll also want to look into the split function.
A:
Basically, what you need to do is pull out the dates and times from your log into a easy-to-compare format. Enter datetime.
import datetime
def getStatus(log_list, dt, tm):
#filter the list
log_list = [a_log_entry for a_log_entry in log_list if a_log_entry[0] == dt and a_log_entry[1] <= tm]
#sort it
log_list.sort(cmp=lambda x,y: cmp(x[1], y[1]))
if log_list is []:
return 'No status available for this day and time.'
#pull out the status
status_to_return = log_list[-1][2].split('_')[-1].strip()
return status_to_return
if __name__ == '__main__':
in_file = open('a.log', 'rU')
a_list = []
for line in in_file:
if line.strip() is not '': #handle whitespace
a_list.append(line.split(' '))
#convert string dates and times to datetime objects
a_list = [ [datetime.datetime.strptime(el[0], '%d/%m/%Y'),
datetime.datetime.strptime(el[1], '%H:%M:%S'),
el[2]] for el in a_list]
a_date = datetime.datetime(2010, 7, 15)
a_time = datetime.datetime(1900, 1, 1, 16, 1, 0)
print getStatus(a_list, a_date, a_time)
| Reading and comparing lines in a file using Python | I have a file of the following format.
15/07/2010 14:14:13 changed_status_from_Offline_to_Available
15/07/2010 15:01:09 changed_status_from_Available_to_Offline
15/07/2010 15:15:35 changed_status_from_Offline_to_Away became_idle
15/07/2010 15:16:29 changed_status_from_Away_to_Available became_unidle
15/07/2010 15:45:40 changed_status_from_Available_to_Away became_idle
15/07/2010 16:05:40 changed_status_from_Away_to_Available became_unidle
15/07/2010 16:51:39 changed_status_from_Available_to_Offline
20/07/2010 13:07:26 changed_status_from_Offline_to_Available
I need to create a function in python that has to arguments: date and time. It should read the file and return the second status if the date matches and time is less than the time in the function call. That is
Lets say i call the function returnstatus(15/07/2010, 15:10:01).
The function should go to the file and return the status of the user on that day at that time, which in this case is "Offline".
I am a Python newbie and any help would be really appreciated.
| [
"import datetime\nimport time\n\ndef lines( path_to_file ):\n '''Open path_to_file and read the lines one at a time, yielding tuples\n ( date of line, time of line, status before line )'''\n with open( path_to_file ) as theFile:\n for line in theFile:\n line = line.rsplit( \" \", 1 )\n ... | [
1,
0,
0,
-1
] | [
"Try this:\nimport datetime\n\nfilein = open(\"filein\", \"r\")\n\nclass Status: \n def __init__(self, date, time, status):\n print date.split('/')\n day, month, year = map(int, date.split('/'))\n hour, minute, second = map(int, time.split(':'))\n self.date_and_time = datetime.datet... | [
-1,
-1
] | [
"compare",
"file",
"python"
] | stackoverflow_0003404686_compare_file_python.txt |
Q:
Python: urlopen not downloading the entire site
Greetings,
I have done:
import urllib
site = urllib.urlopen('http://www.weather.com/weather/today/Temple+TX+76504')
site_data = site.read()
site.close()
but it doesn't compare to viewing the source when loaded in firefox.
I suspected the user agent and did this:
class AppURLopener(urllib.FancyURLopener):
version = "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.2.8) Gecko/20100722 Ubuntu/10.04 (lucid) Firefox/3.6.8"
urllib._urlopener = AppURLopener()
and downloaded it, but it still doesn't download the whole website.
Can someone please help me do user agent switching, if that is the likely culprit?
Thanks,
Narnie
A:
It's more likely that there is an iframe in the code or that javascript is modifying the DOM. If theres an iframe, you'll have to parse the page to get the url for the iframe or just do it manually if it's a one-off. If it's javascript, I hear that selenium-rc is good but have no first hand experience with it.
A:
downloaded page displayed locally may look different from several reasons, like that there are relative links (can be fixed adding e.g. <base href="http://www.weather.com/today/"> into the page head element), or non-functional ajax requests (see Ways to circumvent the same-origin policy).
| Python: urlopen not downloading the entire site | Greetings,
I have done:
import urllib
site = urllib.urlopen('http://www.weather.com/weather/today/Temple+TX+76504')
site_data = site.read()
site.close()
but it doesn't compare to viewing the source when loaded in firefox.
I suspected the user agent and did this:
class AppURLopener(urllib.FancyURLopener):
version = "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.2.8) Gecko/20100722 Ubuntu/10.04 (lucid) Firefox/3.6.8"
urllib._urlopener = AppURLopener()
and downloaded it, but it still doesn't download the whole website.
Can someone please help me do user agent switching, if that is the likely culprit?
Thanks,
Narnie
| [
"It's more likely that there is an iframe in the code or that javascript is modifying the DOM. If theres an iframe, you'll have to parse the page to get the url for the iframe or just do it manually if it's a one-off. If it's javascript, I hear that selenium-rc is good but have no first hand experience with it.\n"... | [
3,
2
] | [] | [] | [
"python",
"urllib",
"urlopen"
] | stackoverflow_0003463533_python_urllib_urlopen.txt |
Q:
TurboMail 3 with Pylons 1.0 - MailNotEnabledException
I am trying to setup TurboMail 3 with Pylons 1.0
Followed the docs here
I have added this to the development.ini
[DEFAULT]
...
mail.on = true
mail.manager = immediate
mail.transport = smtp
mail.smtp.server = localhost
and my app_globals.py looks like:
"""The application's Globals object"""
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
class Globals(object):
def __init__(self, config):
self.cache = CacheManager(**parse_cache_config_options(config))
from turbomail.adapters import tm_pylons
tm_pylons.start_extension()
My controller has this method:
def submit(self):
message = Message("from@example.com", "to@example.com", "Hello World")
message.plain = "TurboMail is really easy to use."
message.send()
The problem is that I am getting this error when message.send() is been called:
MailNotEnabledException: An attempt was made to use a facility of the TurboMail framework but outbound mail hasn't been enabled in the config file [via mail.on]
I don't know what am I missing here?
It all seems right according to the docs!
Thanks
A:
Pylons 1.0 made several backwards-incompatible changes to how (and when) the configuration is stored in a global object. In this case, the configuration is no longer loaded when the Globals object is instantiated. Instead, you will have to change your code to the following:
import atexit
from turbomail import interface
from turbomail.adapters import tm_pylons
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
class Globals(object):
def __init__(self, config):
self.cache = CacheManager(**parse_cache_config_options(config))
atexit.register(tm_pylons.shutdown_extension)
interface.start(tm_pylons.FakeConfigObj(config))
The above (atexit and interface.start) is exactly what the start_extension() code does.
I'll be releasing an updated TurboMail to allow passing the configuration as an argument to start_extension(), which should clear this up in a more sane way.
| TurboMail 3 with Pylons 1.0 - MailNotEnabledException | I am trying to setup TurboMail 3 with Pylons 1.0
Followed the docs here
I have added this to the development.ini
[DEFAULT]
...
mail.on = true
mail.manager = immediate
mail.transport = smtp
mail.smtp.server = localhost
and my app_globals.py looks like:
"""The application's Globals object"""
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
class Globals(object):
def __init__(self, config):
self.cache = CacheManager(**parse_cache_config_options(config))
from turbomail.adapters import tm_pylons
tm_pylons.start_extension()
My controller has this method:
def submit(self):
message = Message("from@example.com", "to@example.com", "Hello World")
message.plain = "TurboMail is really easy to use."
message.send()
The problem is that I am getting this error when message.send() is been called:
MailNotEnabledException: An attempt was made to use a facility of the TurboMail framework but outbound mail hasn't been enabled in the config file [via mail.on]
I don't know what am I missing here?
It all seems right according to the docs!
Thanks
| [
"Pylons 1.0 made several backwards-incompatible changes to how (and when) the configuration is stored in a global object. In this case, the configuration is no longer loaded when the Globals object is instantiated. Instead, you will have to change your code to the following:\nimport atexit\nfrom turbomail import ... | [
3
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003458344_pylons_python.txt |
Q:
Python compile all non-words except dot[.]
I am trying to break a line on all non-word patterns except .(dot)
Usually I guess it can be done as [\W ^[.]] in java, but how to I do in python?
A:
>>> import re
>>> the_string="http://hello-world.com"
>>> re.findall(r'[\w.]+',the_string)
['http', 'hello', 'world.com']
A:
A very good reference for Python's regular expression module is available here. Following should do the trick for you.
import re
re.split(r'[\w.]+', text_string)
Or,
import re
re.findall('[^\w.]+', text_string)
A:
Your Java syntax is off, to begin with. This is what you were trying for:
[\W&&[^.]]
That matches a character from the intersection of the sets described by "any non-word character" and "any character except ." But that's overkill when you can just use:
[^\w.]
...or, "any character that's not a word character or .". It's the same in Python (and in most other flavors, too), though you probably want to match one or more of the characters:
re.split(r'[^\w.]+', the_string)
But it's probably simpler to use @gnibbler's approach of matching the parts that you want to keep, not the ones you want to throw away:
re.findall(r'[\w.]+', the_string)
A:
I'm assuming that you want to split a string on all non-word patterns except a dot.
Edit: Python doesn't support the Java-style regex syntax that you are using. I'd suggest first replacing all dots with a long string, then splitting the string, then putting the dots back in.
import re
long_str = "ABCDEFGH"
str = str.replace('.', long_str)
result = re.split(r'\W', str)
Then as you are using result, replace all the long_str sequences with a dot again.
This is a very bad solution, but it works.
| Python compile all non-words except dot[.] | I am trying to break a line on all non-word patterns except .(dot)
Usually I guess it can be done as [\W ^[.]] in java, but how to I do in python?
| [
">>> import re\n>>> the_string=\"http://hello-world.com\"\n>>> re.findall(r'[\\w.]+',the_string)\n['http', 'hello', 'world.com']\n\n",
"A very good reference for Python's regular expression module is available here. Following should do the trick for you.\nimport re\nre.split(r'[\\w.]+', text_string)\n\nOr,\nimpor... | [
4,
1,
1,
0
] | [
"Python has a convenience function for that\n>>> s = \"ab.cd.ef.gh\"\n>>> s.split(\".\")\n['ab', 'cd', 'ef', 'gh']\n\n"
] | [
-1
] | [
"python",
"regex"
] | stackoverflow_0003463650_python_regex.txt |
Q:
M2Crypto: verifying DSA signatures
I'm having trouble verifying DSA signatures using Python/M2Crypto. The signatures are generated in Java, using standard java.security.Signature class, with Sun's crypto provider and SHA1withDSA algorithm designation.
Here's some shell output:
>>> pk
<M2Crypto.DSA.DSA_pub instance at 0x20b6a28>
>>> sig = '302c02141c4bbb218215ebfec57288059ce814dc430d849502144dd0c581bf2213aff79d17eb37c939e120a97bd2'.decode('hex')
>>> data ='0501...9794'.decode('hex')
>>> pk.verify_asn1(sig, data)
------------------------------------------------------------
Traceback (most recent call last):
...
DSAError: wrong tag
The signature value seems OK to me, it looks like a proper ASN.1 encoded sequence of two integers (0x302c designates a 44-byte sequence, and 0x0214 designates a 20-byte integer), which is the standard encoding of DSA signatures.
Since the DSA_pub.verify_asn1 method isn't even documented, I also tried using the documented DSA_pub.verify method, but still no cigar:
>>> r = sig[4:24]
>>> s = sig[26:]
>>> md = sha1(data).digest()
>>> pk.verify(md, r, s)
------------------------------------------------------------
Traceback (most recent call last):
...
DSAError: encoding error
The docs state that all the parameters should be "byte strings", but the verify method somehow manages to raise an encoding error.
I also tried reversing r and s, to check for potential endianness problems but that didn't help.
What am I doing wrong?
A:
Found a solution in the tests: http://svn.osafoundation.org/m2crypto/trunk/tests/test_dsa.py
The verify_asn1 method should be used as follows:
>>> pk.verify_asn1(sha1(data).digest(), sig)
| M2Crypto: verifying DSA signatures | I'm having trouble verifying DSA signatures using Python/M2Crypto. The signatures are generated in Java, using standard java.security.Signature class, with Sun's crypto provider and SHA1withDSA algorithm designation.
Here's some shell output:
>>> pk
<M2Crypto.DSA.DSA_pub instance at 0x20b6a28>
>>> sig = '302c02141c4bbb218215ebfec57288059ce814dc430d849502144dd0c581bf2213aff79d17eb37c939e120a97bd2'.decode('hex')
>>> data ='0501...9794'.decode('hex')
>>> pk.verify_asn1(sig, data)
------------------------------------------------------------
Traceback (most recent call last):
...
DSAError: wrong tag
The signature value seems OK to me, it looks like a proper ASN.1 encoded sequence of two integers (0x302c designates a 44-byte sequence, and 0x0214 designates a 20-byte integer), which is the standard encoding of DSA signatures.
Since the DSA_pub.verify_asn1 method isn't even documented, I also tried using the documented DSA_pub.verify method, but still no cigar:
>>> r = sig[4:24]
>>> s = sig[26:]
>>> md = sha1(data).digest()
>>> pk.verify(md, r, s)
------------------------------------------------------------
Traceback (most recent call last):
...
DSAError: encoding error
The docs state that all the parameters should be "byte strings", but the verify method somehow manages to raise an encoding error.
I also tried reversing r and s, to check for potential endianness problems but that didn't help.
What am I doing wrong?
| [
"Found a solution in the tests: http://svn.osafoundation.org/m2crypto/trunk/tests/test_dsa.py\nThe verify_asn1 method should be used as follows:\n>>> pk.verify_asn1(sha1(data).digest(), sig)\n\n"
] | [
4
] | [] | [] | [
"digital_signature",
"dsa",
"m2crypto",
"python"
] | stackoverflow_0003454523_digital_signature_dsa_m2crypto_python.txt |
Q:
What is a .pyc_dis file?
I have a folder that has a .pyc_dis file from a module. What can I do with it? How do I run it? What does this file even come from?
I couldn't find any information with a Google search.
Thanks.
A:
it's probably a disassembled python bytecode obtained by decompyle.
you can generate similar data like this:
>>> import code, dis
>>> c = code.compile_command('x = []; x.append("foo")')
>>> dis.disassemble(c)
1 0 BUILD_LIST 0
3 STORE_NAME 0 (x)
6 LOAD_NAME 0 (x)
9 LOAD_ATTR 1 (append)
12 LOAD_CONST 0 ('foo')
15 CALL_FUNCTION 1
18 PRINT_EXPR
19 LOAD_CONST 1 (None)
dos the file content look similar?
the bytecode disassembly is not practically useful, but can be used (and is used by decompyle disassembler) if one wants to try to reconstruct the python source code from .pyc file.
UPDATE
e.g. when you run
$ decompyle --showasm -o ./ app.pyc
the app.pyc_dis file containing the bytecode analysis is generated in the current directory, and in my simple example its content is:
0 BUILD_LIST_0 ''
3 STORE_NAME 'x'
6 LOAD_NAME 'x'
9 LOAD_ATTR 'append'
12 LOAD_CONST 'foo'
15 CALL_FUNCTION_1 ''
18 POP_TOP ''
19 LOAD_CONST ''
22 RETURN_VALUE ''
x = []
x.append('foo')
| What is a .pyc_dis file? | I have a folder that has a .pyc_dis file from a module. What can I do with it? How do I run it? What does this file even come from?
I couldn't find any information with a Google search.
Thanks.
| [
"it's probably a disassembled python bytecode obtained by decompyle.\nyou can generate similar data like this:\n>>> import code, dis\n>>> c = code.compile_command('x = []; x.append(\"foo\")')\n>>> dis.disassemble(c)\n 1 0 BUILD_LIST 0\n 3 STORE_NAME 0 (x)\n ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003464145_python.txt |
Q:
Django select options
I'm making an app that has a file name field, an upload file field and a select. Lets say I have something like this for the select
<select name="menu">
<option value="0" selected> select imp </option>
<option value="1"> imp 1 </option>
<option value="2"> imp 2 </option>
<option value="3"> imp 3 </option>
<option value="4"> imp 4 </option>
</select>
<input type="submit" value="Upload" />
I have the file upload working with this class
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(widget=forms.FileInput())
How should the class look with the select added to it?
Or how can I use the file upload form and get the value from the select, and based on that value do an action?
A:
You need to use a ChoiceField:
IMP_CHOICES = (
('1', 'imp 1'),
('2', 'imp 2'),
('3', 'imp 3'),
('4', 'imp 4'),
)
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(widget=forms.FileInput())
imp = forms.ChoiceField(choices=IMP_CHOICES)
| Django select options | I'm making an app that has a file name field, an upload file field and a select. Lets say I have something like this for the select
<select name="menu">
<option value="0" selected> select imp </option>
<option value="1"> imp 1 </option>
<option value="2"> imp 2 </option>
<option value="3"> imp 3 </option>
<option value="4"> imp 4 </option>
</select>
<input type="submit" value="Upload" />
I have the file upload working with this class
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(widget=forms.FileInput())
How should the class look with the select added to it?
Or how can I use the file upload form and get the value from the select, and based on that value do an action?
| [
"You need to use a ChoiceField:\nIMP_CHOICES = (\n ('1', 'imp 1'),\n ('2', 'imp 2'),\n ('3', 'imp 3'),\n ('4', 'imp 4'),\n)\n\nclass UploadFileForm(forms.Form):\n title = forms.CharField(max_length=50)\n file = forms.FileField(widget=forms.FileInput())\n imp = forms.ChoiceField(choices=IMP_CHO... | [
12
] | [] | [] | [
"combobox",
"django",
"drop_down_menu",
"forms",
"python"
] | stackoverflow_0003463700_combobox_django_drop_down_menu_forms_python.txt |
Q:
How to simply read in input from stdin delimited by space or spaces
Hello I'm a trying to learn python,
In C++ to read in string from stdin I simply do
string str;
while (cin>>str)
do_something(str)
but in python, I have to use
line = raw_input()
then
x = line.split()
then I have to loop through the list x to access each str to do_something(str)
this seems like a lot of code just to get each string delimited by space or spaces
so my question is, is there a easier way?
A:
Python doesn't special-case such a specific form of input for you, but it's trivial to make a little generator for it of course:
def fromcin(prompt=None):
while True:
try: line = raw_input(prompt)
except EOFError: break
for w in line.split(): yield w
and then, in your application code, you loop with a for statement (usually the best way to loop at application-code level):
for w in fromcin():
dosomething(w)
A:
There isn't really an "easier" way, since Python doesn't have built-in formatted string functions like C++ does with iostream.
That said, you could shorten your code by combining the operations:
for str in raw_input().split():
do_something(str)
A:
map(do_something, line.split())
| How to simply read in input from stdin delimited by space or spaces | Hello I'm a trying to learn python,
In C++ to read in string from stdin I simply do
string str;
while (cin>>str)
do_something(str)
but in python, I have to use
line = raw_input()
then
x = line.split()
then I have to loop through the list x to access each str to do_something(str)
this seems like a lot of code just to get each string delimited by space or spaces
so my question is, is there a easier way?
| [
"Python doesn't special-case such a specific form of input for you, but it's trivial to make a little generator for it of course:\ndef fromcin(prompt=None):\n while True:\n try: line = raw_input(prompt)\n except EOFError: break\n for w in line.split(): yield w\n\nand then, in your application code, you lo... | [
6,
0,
0
] | [] | [] | [
"python",
"raw_input",
"stdin"
] | stackoverflow_0003464212_python_raw_input_stdin.txt |
Q:
I can retrieve values from datastore
I want to retrieve some values I put in the data store with a model class name "Ani" and I have tried using the script below to do that but I am having problem with. Can someone please, help me with it
import random
import getpass
import sys
# Add the Python SDK to the package path.
# Adjust these paths accordingly.
sys.path.append('/root/google_appengine')
sys.path.append('/root/google_appengine/lib/yaml/lib')
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db
import models
# Your app ID and remote API URL path go here.
APP_ID = 'silasanio'
REMOTE_API_PATH = '/remote_api'
def auth_func():
email_address = raw_input('Email address: ')
password = getpass.getpass('Password: ')
return email_address, password
def initialize_remote_api(app_id=APP_ID,
path=REMOTE_API_PATH):
remote_api_stub.ConfigureRemoteApi(
app_id,
path,
auth_func)
remote_api_stub.MaybeInvokeAuthentication()
def main():
initialize_remote_api()
Meanvalue = []
result = db. ("SELECT * FROM Ani ORDER BY date DESC LIMIT 1")
for res in result:
Meanvalue = res.mean
std_dev = res.stdev
print(mean)
if __name__ == '__main__':
main()
I am getting the error below:
raise KindError('No implementation for kind \'%s\'' % kind)
google.appengine.ext.db.KindError: No implementation for kind 'Ani'
Please, I need some help with it.
Thanks
A:
You need to import the file where you define the class Ani before you can run queries on the data.
| I can retrieve values from datastore | I want to retrieve some values I put in the data store with a model class name "Ani" and I have tried using the script below to do that but I am having problem with. Can someone please, help me with it
import random
import getpass
import sys
# Add the Python SDK to the package path.
# Adjust these paths accordingly.
sys.path.append('/root/google_appengine')
sys.path.append('/root/google_appengine/lib/yaml/lib')
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db
import models
# Your app ID and remote API URL path go here.
APP_ID = 'silasanio'
REMOTE_API_PATH = '/remote_api'
def auth_func():
email_address = raw_input('Email address: ')
password = getpass.getpass('Password: ')
return email_address, password
def initialize_remote_api(app_id=APP_ID,
path=REMOTE_API_PATH):
remote_api_stub.ConfigureRemoteApi(
app_id,
path,
auth_func)
remote_api_stub.MaybeInvokeAuthentication()
def main():
initialize_remote_api()
Meanvalue = []
result = db. ("SELECT * FROM Ani ORDER BY date DESC LIMIT 1")
for res in result:
Meanvalue = res.mean
std_dev = res.stdev
print(mean)
if __name__ == '__main__':
main()
I am getting the error below:
raise KindError('No implementation for kind \'%s\'' % kind)
google.appengine.ext.db.KindError: No implementation for kind 'Ani'
Please, I need some help with it.
Thanks
| [
"You need to import the file where you define the class Ani before you can run queries on the data. \n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003420699_google_app_engine_python.txt |
Q:
What is the subprocess equivalent of passing "b" to os.popen2?
In Python 2.x, os.popen(command, "b") gives me a binary stream of the given command's output. This is primarily important on Windows, where binary and text streams actually give you different bytes.
The subprocess module is supposed to replace os.popen and the other child-process spawning APIs. However, the conversion docs don't talk about dealing with the "b" mode at all. How do you get a binary output stream using subprocess?
A:
It does by default, unless you're doing Popen(..., universal_newlines=True).
class Popen(object):
[...]
def __init__(self, ...):
[...]
if p2cwrite is not None:
self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
if c2pread is not None:
if universal_newlines:
self.stdout = os.fdopen(c2pread, 'rU', bufsize)
else:
self.stdout = os.fdopen(c2pread, 'rb', bufsize)
if errread is not None:
if universal_newlines:
self.stderr = os.fdopen(errread, 'rU', bufsize)
else:
self.stderr = os.fdopen(errread, 'rb', bufsize)
| What is the subprocess equivalent of passing "b" to os.popen2? | In Python 2.x, os.popen(command, "b") gives me a binary stream of the given command's output. This is primarily important on Windows, where binary and text streams actually give you different bytes.
The subprocess module is supposed to replace os.popen and the other child-process spawning APIs. However, the conversion docs don't talk about dealing with the "b" mode at all. How do you get a binary output stream using subprocess?
| [
"It does by default, unless you're doing Popen(..., universal_newlines=True).\nclass Popen(object):\n [...]\n def __init__(self, ...):\n [...]\n if p2cwrite is not None:\n self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)\n if c2pread is not None:\n if universal_newlin... | [
2
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003464589_python_subprocess.txt |
Q:
Django:How can I ensure that a view can only be directed from another view
I have two views
def view1(request):
do something
return HttpResponseRedirect(reverse(view2), args1)
Now I need view2 to only work if it's referred by view1. How do I do that? I did read it somewhere, not able to recollect
@somefilter
def view2(request):
do something
#view2 will only be referred from view1, else Http404
A:
I think you should check for the HTTP_REFERER HTTP header. See the documentation. Here is a Django snippet that gives you a decorator to check for referrers.
| Django:How can I ensure that a view can only be directed from another view | I have two views
def view1(request):
do something
return HttpResponseRedirect(reverse(view2), args1)
Now I need view2 to only work if it's referred by view1. How do I do that? I did read it somewhere, not able to recollect
@somefilter
def view2(request):
do something
#view2 will only be referred from view1, else Http404
| [
"I think you should check for the HTTP_REFERER HTTP header. See the documentation. Here is a Django snippet that gives you a decorator to check for referrers. \n"
] | [
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0003463698_django_django_views_python.txt |
Q:
Throwing exception in Python and reading the message in jQuery
How can I throw an exception on my server and have the exception's message be read in JavaScript (I'm using AJAX with jQuery). My server environment is Google App Engine (Python).
Here's my server code:
def post(self):
answer_text = util.escapeText(self.request.get("answer"))
# Validation
if ( len(str(answer_text)) < 3):
raise Exception("Answer text must be at least 2 characters long.")
return
And here's the AJAX request:
$.ajax({
type: "POST",
url: "/store_answer.html",
data: "question_id=" + question_id +"&answer="+answer,
success: function(responseText){
handleSuccessfulAnswer(question_id);
},
error: function(responseText){
// TODO: How to get the exception message here???
alert("???????????");
},
complete: function(data) {
submitCompleted(submitName, "Submit");
}
});
Thanks!
A:
If you have debug=True in your WSGI app configuration, the stack trace from your exception will get populated to the HTTP response body, and you can parse your message out of the stack trace client side.
Don't do this, though. It's insecure, and a bad design choice. For predictable, recoverable error conditions, you should either be catching the exception or not throwing one at all, e.g.:
if ( len(str(answer_text)) < 3):
self.error(500)
self.response.out.write("Answer text must be at least 2 characters long.")
return
A:
On the server, you need to catch the exception in a try/except block and turn it into a proper HTTP error (with code 500, generic server error, if a server error is what's happened -- 3xx if the problem is with the request, &c -- see here for all the HTTP status codes) with the Response's set_status method.
| Throwing exception in Python and reading the message in jQuery | How can I throw an exception on my server and have the exception's message be read in JavaScript (I'm using AJAX with jQuery). My server environment is Google App Engine (Python).
Here's my server code:
def post(self):
answer_text = util.escapeText(self.request.get("answer"))
# Validation
if ( len(str(answer_text)) < 3):
raise Exception("Answer text must be at least 2 characters long.")
return
And here's the AJAX request:
$.ajax({
type: "POST",
url: "/store_answer.html",
data: "question_id=" + question_id +"&answer="+answer,
success: function(responseText){
handleSuccessfulAnswer(question_id);
},
error: function(responseText){
// TODO: How to get the exception message here???
alert("???????????");
},
complete: function(data) {
submitCompleted(submitName, "Submit");
}
});
Thanks!
| [
"If you have debug=True in your WSGI app configuration, the stack trace from your exception will get populated to the HTTP response body, and you can parse your message out of the stack trace client side.\nDon't do this, though. It's insecure, and a bad design choice. For predictable, recoverable error conditions, ... | [
3,
2
] | [] | [] | [
"ajax",
"google_app_engine",
"jquery",
"python"
] | stackoverflow_0003464434_ajax_google_app_engine_jquery_python.txt |
Q:
Is there way to make costum signal when Manytomany relations created? Django!
Is there way to make custom signal when ManyToMany relations created?
A:
Without knowing more details about what you are trying to accomplish I'd suggest that you take a look at this previously asked question. If this is not what you are looking for then posting more details (including code) about what you want to do will help.
| Is there way to make costum signal when Manytomany relations created? Django! | Is there way to make custom signal when ManyToMany relations created?
| [
"Without knowing more details about what you are trying to accomplish I'd suggest that you take a look at this previously asked question. If this is not what you are looking for then posting more details (including code) about what you want to do will help.\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_signals",
"python"
] | stackoverflow_0003462294_django_django_models_django_signals_python.txt |
Q:
Why does Cassandra act strange with byte keys (with Lazyboy)?
I wrote a test program for testing Cassandra, and I had problems reading data. Seems like Cassandra sometimes takes one key for another.
Here is my test program :
from lazyboy import *
from lazyboy.key import Key
import uuid
import random
class TestItemKey(Key):
def __init__(self, key=None):
Key.__init__(self, "TestMX", "TestCF", key)
class TestItem(record.Record):
def __init__(self, *args, **kwargs):
record.Record.__init__(self, *args, **kwargs)
self.key = TestItemKey(uuid.uuid1().bytes)
connection.add_pool('TestMX', ['localhost:9160'])
t1 = TestItem({'test':'foo'})
t1.key = TestItemKey(uuid.UUID('3cead15a-a54e-11df-87a2-000c298d2724').bytes)
t2 = TestItem({'test':'bar'})
t2.key = TestItemKey(uuid.UUID('3cebc15a-a54e-11df-87a2-000c298d2724').bytes)
t1.save()
t2.save()
print TestItem().load(t1.key.clone())
print TestItem().load(t2.key.clone())
(The chosen UUIDs are an example of the ones causing problems)
Here is the output of this script :
root@ubuntu:/mnt/hgfs/TestMX# python test.py
TestItem: {'test': 'foo'}
TestItem: {'test': 'foo'}
Instead of the expected result :
root@ubuntu:/mnt/hgfs/TestMX# python test.py
TestItem: {'test': 'foo'}
TestItem: {'test': 'bar'}
Note that the script usually works great with other randomely-chosen UUIDs, but sometimes not...
A:
Sounds a lot like you're hitting https://issues.apache.org/jira/browse/CASSANDRA-1235 which is fixed in the 0.6 branch and will be in 0.6.5, the next stable release.
| Why does Cassandra act strange with byte keys (with Lazyboy)? | I wrote a test program for testing Cassandra, and I had problems reading data. Seems like Cassandra sometimes takes one key for another.
Here is my test program :
from lazyboy import *
from lazyboy.key import Key
import uuid
import random
class TestItemKey(Key):
def __init__(self, key=None):
Key.__init__(self, "TestMX", "TestCF", key)
class TestItem(record.Record):
def __init__(self, *args, **kwargs):
record.Record.__init__(self, *args, **kwargs)
self.key = TestItemKey(uuid.uuid1().bytes)
connection.add_pool('TestMX', ['localhost:9160'])
t1 = TestItem({'test':'foo'})
t1.key = TestItemKey(uuid.UUID('3cead15a-a54e-11df-87a2-000c298d2724').bytes)
t2 = TestItem({'test':'bar'})
t2.key = TestItemKey(uuid.UUID('3cebc15a-a54e-11df-87a2-000c298d2724').bytes)
t1.save()
t2.save()
print TestItem().load(t1.key.clone())
print TestItem().load(t2.key.clone())
(The chosen UUIDs are an example of the ones causing problems)
Here is the output of this script :
root@ubuntu:/mnt/hgfs/TestMX# python test.py
TestItem: {'test': 'foo'}
TestItem: {'test': 'foo'}
Instead of the expected result :
root@ubuntu:/mnt/hgfs/TestMX# python test.py
TestItem: {'test': 'foo'}
TestItem: {'test': 'bar'}
Note that the script usually works great with other randomely-chosen UUIDs, but sometimes not...
| [
"Sounds a lot like you're hitting https://issues.apache.org/jira/browse/CASSANDRA-1235 which is fixed in the 0.6 branch and will be in 0.6.5, the next stable release.\n"
] | [
2
] | [] | [] | [
"cassandra",
"python",
"uuid"
] | stackoverflow_0003459086_cassandra_python_uuid.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.