Re: Reverse Iteration Through Integers
On Sun, Oct 18, 2009 at 10:53 PM, Jabba Laci jabba.l...@gmail.com wrote: Hi, Would someone explain how str[::-1] work? I'm new to Python and I only saw so far the str[begin:end] notation. What is the second colon? Specifies the step value, as in: foo[start:stop:step] When not specified it, defaults to 1. So foo[::-1] gives the entire sequence backwards. Analogously, foo[::2] gives every other item in the sequence, forwards. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
On Oct 19, 3:53 pm, Jabba Laci jabba.l...@gmail.com wrote: Would someone explain how str[::-1] work? I'm new to Python and I only saw so far the str[begin:end] notation. What is the second colon? Slice notation is of the form [start:stop:step]. start defaults to the start of the sequence, stop to the end, and step to 1. So a slice of [::-1] returns the full sequence in reverse, stepping back one character at a time from the end of the sequence to the beginning. The only mention I could find was http://docs.python.org/dev/3.0/library/functions.html#slice -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Sunday, 18 October 2009 11:31:19 Paul Rubin wrote: Hendrik van Rooyen hend...@microcorp.co.za writes: Standard Python idiom: if key in d: d[key] += value else: d[key] = value The issue is that uses two lookups. If that's ok, the more usual idiom is: d[key] = value + d.get(key, 0) I was actually just needling Aahz a bit. The point I was trying to make subliminally, was that there is a relative cost of double lookup for all cases versus exceptions for some cases. - Depending on the frequency of some, I would expect a breakeven point. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
weekdays in range
(Sorry if this shows up twice.) Can someone think of an easy way to calculate the number of weekdays between two calendar dates (in Python)? Thankee. -- http://mail.python.org/mailman/listinfo/python-list
Re: weekdays in range
I'm using weekdays as a proxy for days when the US stock market is open. (I'll miss holidays.) The application is pricing CALL and PUT options. Speed is not a problem. The number of days will typically be between 1 and 254. -- http://mail.python.org/mailman/listinfo/python-list
CALL FOR PAPERS: TOOLS EUROPE 2010
== CALL FOR PAPERS (Deadline: January 22, 2010) TOOLS EUROPE 2010 48th International Conference Objects, Models, Components, Patterns Co-located with *** International Conference on Model Transformation (ICMT 2010) *** *** International Conference on Software Composition (SC 2010) *** *** International Conference on Tests and Proofs (TAP 2010) *** Málaga - Spain, 28 June - 02 July 2010 http://malaga2010.lcc.uma.es/ == TOOLS EUROPE is devoted to the combination of technologies that have emerged as a result of object technology becoming mainstream. Like its predecessors, TOOLS EUROPE combines an emphasis on quality with a strong practical focus. Started in 1989, TOOLS conferences, held in Europe, the USA, Australia, China and Eastern Europe, have played a major role in the development of object technology; many of seminal concepts were first presented at TOOLS. After an interruption of four years, the conference was revived in 2007 to reflect the maturing of the field and the new challenges ahead and has become a yearly event. Contributions are solicited on all aspects of object technology and related fields, in particular model-based development, component-based development, and patterns (design, analysis and other applications); more generally, any contribution addressing topics in advanced software technology fall within the scope of TOOLS. Reflecting the practical emphasis of TOOLS, contributions showcasing applications along with a sound conceptual contribution are particularly welcome. Topics include: * Object technology, including programming techniques, languages, tools * Testing of object-oriented systems * Patterns, pattern languages, tool support for patterns * Distributed and concurrent object systems * Real-time object-oriented programming and design * Experience reports, including efforts at standardisation * Applications to safety- and security-related software * Component-based programming, modelling, tools * Aspects and aspect-oriented programming and modelling * Frameworks for component-based development * Trusted and reliable components * Model-driven development and Model-Driven Architecture * Domain specific languages and language design * Tools and frameworks for supporting model-driven development * Language implementation techniques, compilers, run-time systems * Practical applications of program verification and analysis * Open source solutions Reproduction studies All contributions will be subject to a rigorous selection process by the international Program Committee, with a stress on originality, practicality and overall quality. The proceedings will be published in Springer LNBIP. For detailed submission information see the conference page. Important Dates: Papers submission deadline: January 22, 2010 Acceptance notification: March 24, 2010 Camera-ready final copy: April 5, 2010 Conference: June 28 -- July 02, 2010 Conference Chair: Bertrand Meyer, ETH Zürich and Eiffel Software Program Chair: Jan Vitek, Purdue University Publicity Chair: Osmar Santos, University of York Program Committee: Uwe Assman, University of Dresden, Germany Elisa Baniassad, Chinese University of Hong Kong, Hong Kong Alexandre Bergel, University of Chile, Chile Lorenzo Bettini, University of Torino, Italy Judith Bishop, University of Pretoria, South Africa William Cook, University of Texas Austin, USA Sophia Drossopolou, Imperial College London, UK Catherine Dubois, ENSIIE, France Stéphane Ducasse, INRIA Lille, France Manuel Fahndrich, Microsoft Research, USA Harald Gall, University of Zurich, Switzerland Benoit Garbinato, University of Lausanne, Switzerland Angelo Gargantini, University of Bergamo, Italy Jeff Gray, University of Alabama Birmingham, USA Kathryn Gray, University of Cambridge, UK Thomas Gschwind, IBM Research, Switzerland Matthias Hauswith, University of Lugano, Switzerland Nigel Horspool, University of Victoria, Canada Tomas Kalibera, Charles University, Czech Republic Gerti Kappel, Vienna University of Technology, Austria Doug Lea, State University of New York Oswego, USA Shane Markstrum, Brucknell University, USA Peter Müller, ETH Zurich, Switzerland Oscar Nierstrasz, University of Bern, Switzerland James Noble, Victoria University of Wellington, New Zealand Nate Nystrom, University of Texas Arlington, USA Manuel Oriol, University of York, UK Jonathan Ostroff, York University, Canada Richard Paige, University of York, UK Shaz Qadeer, Microsoft Research, USA Awais Rashid, Lancaster University, UK Vivek Sarkar, Rice University, USA Doug Schmidt, Vanderbilt University, USA Manuel Serrano, INRIA Sophia Antipolis, France Peter Thiemann, University of
Re: restriction on sum: intentional bug?
On Oct 16, 6:53 pm, ryles ryle...@gmail.com wrote: Then you probably haven't read through these discussions: sum and strings:http://mail.python.org/pipermail/python-list/2006-August/subject.html summing a bunch of numbers:http://mail.python.org/pipermail/python-dev/2003-April/subj You meant: sum and strings: http://mail.python.org/pipermail/python-list/2006-August/subject.html summing a bunch of numbers: http://mail.python.org/pipermail/python-dev/2003-April/subject.html -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Mon, 19 Oct 2009 08:51:44 +0200, Hendrik van Rooyen wrote: The point I was trying to make subliminally, was that there is a relative cost of double lookup for all cases versus exceptions for some cases. - Depending on the frequency of some, I would expect a breakeven point. There is, at least according to my (long distant and only barely remembered) tests. Setting up a try...except is very cheap, about as cheap as a pass statement. That is: d = {1: None} try: x = d[1] except KeyError: print This can't happen is approximately as costly as: d = {1: None} pass x = d[1] under Python 2.5. However, catching an exception is more expensive, approximately ten times more so. Doing a lookup twice falls somewhere between the two, closer to the cheap side than the expensive. So according to my rough estimates, it is faster to use the try...except form so long as the number of KeyErrors is less than about one in six, give or take. If KeyError is more common than that, it's cheaper to do a test first, say with d.has_key(). Using the `in` operator is likely to be faster than has_key(), which will shift the break-even point. (The above numbers are from memory and should be taken with a large pinch of salt. Even if they are accurate for me, they will likely be different on other machines, and will depend on the actual keys in the dict. In other words, your mileage may vary.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
smtplib send mail dns resolve problem
hello everyone, I am using smtplib to send email, and i meet such a problem: my email smtp server hostname can be parsed to 5 ips, for example: ** my email smtp server hostname: email-my.local.com ips through dns parse: 1.1.1.1 1.1.1.12 1.1.13.1 1.1.1.14 1.1.1.15 ** but when i send mail using smtplib, i was always using one ip, no dns re-resolve happened, (for example: only use 1.1.1.12). I checked smtplib src code, but i can't find anything strange; here is my smtplib send mail client code: for i in range(1000): server = smtplib.SMTP(host) try: server.sendmail(fromaddr, toaddr, msg) except Exception, e: logger.warning('sendmail exception') else: pass finally: server.quit() time.sleep(0.3) Can anyone give some tips? Thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: (from stdlib-sig) ctypes or struct from an h file
Ok I see your point that C is ambiguous concerning compiler implementation. I think #pragma pack should work out the padding issue but I'm not sure if the floating point issue is solvable. I don't have an idea for solving that one... On Sun, Oct 18, 2009 at 11:14 PM, Erik Max Francis m...@alcyone.com wrote: Yuvgoog Greenle wrote: I'd like to clarify the use case. Lets say you're writing a client and a server, one is in python and the other is C. If these 2 programs need to pass binary information between them (lets say over a socket) there are 2 options, it could be nice if you could only write the struct once (either in python or in C) without any Cython or C extension (for portability and ease of development's sake). It's not as simple as that. You have to know the binary format layouts (say, for floating point numbers) and struct padding that's used (since it can be inserted arbitrarily) on the C side of things, not to mention you have to arrange the whole the to be put into consistent (network) byte order. Both sides have to take care of this, since if the server and client are running on different architectures, there's no guarantees any of these things will be the same. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Skype erikmaxfrancis Diplomacy and defense are not substitutes for one another. Either alone would fail. -- John F. Kennedy, 1917-1963 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: print()
Gabriel Genellina wrote: snip but the new str.format() originally suggested by Dave Angel is better: s = {0:03.02f}% done.format(100.0-100.0*(size/tot)) (BTW, why 03.02f? The output will always have at least 4 chars, so 03 doesn't mean anything... Maybe you want {0:06.2f} (three places before the decimal point, two after it, filled with 0's on the left)?) I deliberately gave an example where every specifier was a different digit, so I could easily describe what each part did. It was intended to be understood, not copied. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
Paul Rubin: If you want to peel off digits from an int one by one without string conversions, it's easiest to do that in reverse order: n = 961 digits = [] while n 0: n,d = divmod(n, 10) digits.append(d) Look up the docs for divmod for an explanation of that handy function. Now the above gives you a reversed list of digits--what to do with it is an exercise for you ;-). Note that if n=0 then you get the empty list. I think that with Psyco it's better to avoid divmod(). It's very positive to teach novices to always use tests every time they write a function, because it makes their programs less buggy and often allows them to solve the whole programming problem sooner: def reverse(n): Reverse the digits of integer n, ignoring trailing zeros. reverse(12590) 9521 reverse(abc) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for divmod(): 'str' and 'int' [reverse(x) for x in (0, 1, -1, 2, -2L, 100L, -100)] [0, 1, -1, 2, -2L, 1L, -1] [reverse(x) for x in (125, 1250, 123456789)] [521, 521, 987654321] [reverse(x) for x in (0.0, 1.0, -5.3, 125.0, 1.23456e20)] [0, 1.0, -5.2998, 521.0, 654321.0] str(reverse(169883903200298309284038223098439430943092816286 ** 123))[:35] '65852401624276201339740994895755844' # code removed ... if __name__ == __main__: import doctest doctest.testmod() print Doctests done Using tests (and a bit later to use a versioning system) is among the things that have to be taught as soon as possible :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
juno http://github.com/breily/juno it's very easy, uses sqlalchemy as ORM and jinja2 (others can be used if you want) for templates. On Mon, Oct 19, 2009 at 10:24 AM, Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid wrote: flebber a écrit : Hi I have been searching through the vast array of python frameworks http://wiki.python.org/moin/WebFrameworks and its quite astounding the choice available. I am looking at using a web framework for my personal project which isn't actually aimed at developing a website as such. However I deduce that rather than creating a gui application and screen input for data, I can use a web browser for this and have a great array of tools to format input screens and output display formats. Yeps - but remember that a web app will have a couple limitations / drawbacks, specially wrt/ handling complex UI. Since I will be retreiving information from several websites (usually csv files) formatting them and submitting them to a database and creating queries and printouts based on them most frameworks seem to handle this basically with ease and for any complex queries most support SqlAlchemy. Is it simply a case of just picking one and starting and I would find it hard to be dissapointed or is there a few special considerations to make, though I am unsure what they are? Given your specs, forget about monstruosities like Zope, Twisted etc, that will mostly get in the way. You have simple needs, use a simple tool !-) Most obvious ones I am considering are Django (Of course), A pretty good framework, but you'll loose some of it's nice features if you ever want to use an alternate DB layer or templating system. OTHO, most other more flexible frameworks just don't offer this level of integration, so it's may not be such a big deal. Note that Django's ORM, while already pretty good and constently improving, is not as powerful as SLQAlchemy (now nothing prevents you from going down to raw SQL for the more complex queries - and this might be better anyway, since complex queries usually requires to be very fine tuned and tend to not be really portable). The Forms API OTHO is a real winner IMHO. Pylons includes SqlAlchemy, Sql Object and templating and I here turbogears plans to sit on top of this platform. I admit I fail to see what TG brings except for more indirection levels. Zope I am considering but I am a little confused by this. Friendly advice (based on years of working experience): don't waste your time with Zope. The are heaps of others but not sure how to narrow the selection criteria. How/Why woul you split Django and Pylons let alone the others? Django : very strong integration, excellent documentation and support, huge community, really easy to get started with. And possibly a bit more mature and stable... Pylons : more loosely coupled (imply: less integration), based on standard components - which is both a blessing and a curse, specially wrt/ documentation -, requires a good knowledge of Python and the HTTP protocol to get started with. Very powerful and flexible but this comes with a price... Now both are written by talented programmers, and both are pretty good tools. I guess it's more a matter of personal preferences and/or external constraints (PHB etc...) than anything else. A couple other lightweight candidates you migh want to consider are werkzeug and web.py: http://werkzeug.pocoo.org/ http://webpy.org/ Database likely to be MySQl Mmmm If your application is write-heavy, PostgreSQL might be a better choice. Anyway, both Django's ORM and SQLAlchemy work fine with MySQL AFAICT. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for Bioinformatics available and in stock
Sebastian Bassi, this is an piece from the #5: ProtSeq = raw_input(Protein sequence: ).upper() ProtDeg = {A:4,C:2,D:2,E:2,F:2,G:4,H:2, I:3,K:2,L:6,M:1,N:2,P:4,Q:2, R:6,S:6,T:4,V:4,W:1,Y:2} SegsValues = [] for aa in range(len(ProtSeq)): A more pythonic code is: prot_seq = raw_input(Protein sequence: ).upper() prot_deg = {... segs_values = [] for aa in xrange(len(prot_seq)): Note the use of xrange and names_with_underscores. In Python names are usually lower case and their parts are separated by underscores. From #6: segsvalues=[]; segsseqs=[]; segment=protseq[:15]; a=0 == segs_values = [] segs_seqs = [] segment = prot_seq[:15] a = 0 If you want to limit the space in the book the you can pack those lines in a single line, but it's better to keep the underscores. From #18: prop = 100.*cp/len(AAseq) return (charge,prop) == prop = 100.0 * cp / len(aa_seq) return (charge, prop) Adding spaces between operators and after a comma, and a zero after the point improves readability. From #35: import re pattern = [LIVM]{2}.RL[DE].{4}RLE ... rgx = re.compile(pattern) When the pattern gets more complex it's better to show readers to use a re.VERBOSE pattern, to split it on more lines, indent those lines as a program, and add #comments to those lines. The #51 is missing. I like Python and I think Python is fit for bioinformatics purposes, but 3/4 of the purposes of a book like this are to teach bioinformatics first and computer science and Python second. And sometimes a dynamic language isn't fast enough for bioinformatics purposes, so a book about this topic probably has to contain some pieces of C/D/Java code too, to show and discuss implementations of algorithms that require more heavy computations (that are often already implemented inside biopython, etc, but someone has to write those libs too). The purpose here is not to teach how to write industrial-strength C libraries to perform those heavier computations, but to give the reader an idea (in a real lower-level language) how those libraries are actually implemented. Because science abhors black boxes, a scientist must have an idea of how all subsystems she/he/hir is using are working inside (that's why using Mathematica can be bad for a scientist, because such person has to write and here magic happens in the produced paper). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check the exists of a name?
David 71da...@libero.it (D) wrote: D Il Sat, 17 Oct 2009 23:43:36 -0700 (PDT), StarWing ha scritto: I got a idea, use a try...except statement. there are another way to do it ? (I just curious now, because I solve my problem in another way :-) D locals().has_key(myname) D globals().has_key(myname) 1. This excludes builtins. The OP says: `no matter where is it', so that suggests also builins. 2. The more modern invocation would be myname in locals() or myname in globals(). In Python3 the other one isn't supported anymore. -- Piet van Oostrum p...@vanoostrum.org WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
Carl Banks wrote: Consider this thought experiment: class Something(object): def __radd__(self,other): return other + q x = [a,b,c,Something()] If x were passed to .join(), it would throw an exception; but if passed to a sum() without any special casing, it would successfully return abcq. Okay...this is the best argument I've heard for not using .join() {Awards Carl one (1) internet} It's a peculiar thing to do as a programmer, but .join() certainly produces an unexpected behavior which I'd say is worse. And a lot of this discussion has revolved around letting programmers do peculiar things if they want. So as of Carl's example, I'm now pretty solidly in the Stop throwing an exception, just sum the parts even if it's inefficient camp and no longer straddling between that and the .join() camp. But I'm definitely still not in the throwing exceptions is a good thing camp. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
2009/10/18 Steven D'Aprano st...@remove-this-cybersource.com.au: That confuses me. If I call: y = mydict[x] how does my knowledge of what to do if x is not a key relate to whether the language raises an exception, returns an error code, dumps core, or prints He's not the Messiah, he's a very naughty boy to stderr? You seem to be making a distinction of *intent* which, as far as I can tell, doesn't actually exist. What's the difference in intent between these? y = mydict[x] if y == KeyErrorCode: handle_error_condition() process(y) and this? try: y = mydict[x] except KeyError: handle_error_condition() process(y) Nothing -- because both of those are at the level of code where you know what to do with the error condition. But if you weren't -- if, for example, you were in a library routine and had no idea how the routime might be used in the future -- the latter would just become: y = mydict[x] and the problem is passed on until it gets to somebody who does know. In the former case, though, you still need all the error handling code even though you don't know how to handle the error, *and* you need to exit with an error code of your own, *and* your client needs error handling code even though /they/ might not know how to handle the error, and so on. Neither assumes more or less knowledge of what to do in handle_error_condition(). Neither case assumes that the failure of x to be a key is an error: They both assume that calling handle_error_condition() is an appropriate response. That's why they have the overhead that they do. Exceptions don't have one common overhead across all languages that use them. They have different overhead in different languages -- they're very heavyweight in C++ and Java, but lightweight in Python. As others have pointed out, Python exceptions are cheap to set up, but decidedly less cheap to invoke. But I'm not making the efficiency argument, I'm making the clarity argument. I don't /quite/ believe that Premature Optimisation is the root of all evil, but I wouldn't avoid exceptions because of the overhead. In the rare cases where the response to an exceptional condition is time (or resource?)-critical I'd consider that case to need special handling anyway, and so wouldn't treat it as an exception. Python uses exceptions for flow control: Yes, and in some cases I think that's a serious language wart. Not enough to put me off the language, but a serious wart nevertheless. I think exceptions are a beautiful and powerful way of dealing with flow control, much better than returning a special code, and much better than having to check some status function or global variable, as so often happens in C. They're more restricted, and therefore safer, than goto. They're not a panacea but they're very useful. I agree completely -- when they're used in appropriate circumstances. Not when they're not. I think you're confused about what list.index(obj) does. You seem to me to be assuming that [1,2,3].index(5) should return the item in position 5 of the list, and since there isn't one (5 is out of bounds), raise an exception. But that's not what it does. It searches the list and returns the position at which 5 is found. Yes, sorry, brain fade. But my point remains that the authors of index can't know whether the item not being in the list is an error or not, can't know how to handle that case, and so passing it to the client as an exception is an appropriate response. No, it's not being killed from outside the program -- it's being *interrupted* from *inside* the program by the user. Who -- unless AI has advanced further than I thought -- is *outside* the program. -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
On Oct 19, 3:24 am, Tim Chase python.l...@tim.thechases.com wrote: Carl Banks wrote: Consider this thought experiment: class Something(object): def __radd__(self,other): return other + q x = [a,b,c,Something()] If x were passed to .join(), it would throw an exception; but if passed to a sum() without any special casing, it would successfully return abcq. Okay...this is the best argument I've heard for not using .join() {Awards Carl one (1) internet} Well that was my argument in the last post you followed up to, I just used a bad example. Actually this example was described by Dave Angel, so you should give the internet to him. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
File not closed on exception
Hi I thought that file objects were supposed to be garbage-collected and automatically closed once they go out of scope, at least that's what I've been told by more merited Python programmers. I'm also quite sure that this is quite a common assumption in various programs, at least given what opensource code I've seen in my time. However, the following script doesn't work on Windows, since the file is still open when I try to remove it: import os.path def create(): f = file(tmp, w) raise Exception try: create() finally: os.remove(tmp) So, what's the deal exactly, is the file supposed to be garbage- collected (and closed) at the end of create? Thanks! Arve -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
On Oct 19, 7:40 pm, Javier Santana qualo...@gmail.com wrote: junohttp://github.com/breily/juno it's very easy, uses sqlalchemy as ORM and jinja2 (others can be used if you want) for templates. On Mon, Oct 19, 2009 at 10:24 AM, Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid wrote: flebber a écrit : Hi I have been searching through the vast array of python frameworks http://wiki.python.org/moin/WebFrameworksand its quite astounding the choice available. I am looking at using a web framework for my personal project which isn't actually aimed at developing a website as such. However I deduce that rather than creating a gui application and screen input for data, I can use a web browser for this and have a great array of tools to format input screens and output display formats. Yeps - but remember that a web app will have a couple limitations / drawbacks, specially wrt/ handling complex UI. Since I will be retreiving information from several websites (usually csv files) formatting them and submitting them to a database and creating queries and printouts based on them most frameworks seem to handle this basically with ease and for any complex queries most support SqlAlchemy. Is it simply a case of just picking one and starting and I would find it hard to be dissapointed or is there a few special considerations to make, though I am unsure what they are? Given your specs, forget about monstruosities like Zope, Twisted etc, that will mostly get in the way. You have simple needs, use a simple tool !-) Most obvious ones I am considering are Django (Of course), A pretty good framework, but you'll loose some of it's nice features if you ever want to use an alternate DB layer or templating system. OTHO, most other more flexible frameworks just don't offer this level of integration, so it's may not be such a big deal. Note that Django's ORM, while already pretty good and constently improving, is not as powerful as SLQAlchemy (now nothing prevents you from going down to raw SQL for the more complex queries - and this might be better anyway, since complex queries usually requires to be very fine tuned and tend to not be really portable). The Forms API OTHO is a real winner IMHO. Pylons includes SqlAlchemy, Sql Object and templating and I here turbogears plans to sit on top of this platform. I admit I fail to see what TG brings except for more indirection levels. Zope I am considering but I am a little confused by this. Friendly advice (based on years of working experience): don't waste your time with Zope. The are heaps of others but not sure how to narrow the selection criteria. How/Why woul you split Django and Pylons let alone the others? Django : very strong integration, excellent documentation and support, huge community, really easy to get started with. And possibly a bit more mature and stable... Pylons : more loosely coupled (imply: less integration), based on standard components - which is both a blessing and a curse, specially wrt/ documentation -, requires a good knowledge of Python and the HTTP protocol to get started with. Very powerful and flexible but this comes with a price... Now both are written by talented programmers, and both are pretty good tools. I guess it's more a matter of personal preferences and/or external constraints (PHB etc...) than anything else. A couple other lightweight candidates you migh want to consider are werkzeug and web.py: http://werkzeug.pocoo.org/ http://webpy.org/ Database likely to be MySQl Mmmm If your application is write-heavy, PostgreSQL might be a better choice. Anyway, both Django's ORM and SQLAlchemy work fine with MySQL AFAICT. -- http://mail.python.org/mailman/listinfo/python-list After further reading Django does indeed cover a lot of bases. When looking at jinja2 and werkzueg, first thing I noticed is that they are by the same group called pocoo. Second it shows that I must be misunderstanding something, can I really use jinja2 and sqlAlchemy by itself? The werkzeug documentation shows a screencast http://werkzeug.pocoo.org/wiki30/ of making a wiki and uses werkzueg, jinja2 and sqlAlchemy, why werkzueg and jinja2 in combination? And pylons advises use of SqlAlchemy and Mako or choices of Genshi and Jinja2, so what is pylons adding? Might have to do a bit more reading and watch a few more screencasts :-) -- http://mail.python.org/mailman/listinfo/python-list
strange behaviour of colon within string
hello all, i am relatively new to python and i am trying to convert a php app i have over to it using googleapps. anyway here is the problem. i poll ebay API which has in its XML ? xml version=1.0 encoding=utf-8?findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/search/v1/services; however it fails to create the string UNLESS i remove the colon (:) in the http section. i tried to substitute it with chr(58) but it errors the same without showing why. does anyone know what i am doing wrong? is this peculiar to googleapps? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: strange behaviour of colon within string
khany wrote: hello all, i am relatively new to python and i am trying to convert a php app i have over to it using googleapps. anyway here is the problem. i poll ebay API which has in its XML ? xml version=1.0 encoding=utf-8?findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/search/v1/services; however it fails to create the string UNLESS i remove the colon (:) in the http section. i tried to substitute it with chr(58) but it errors the same without showing why. does anyone know what i am doing wrong? is this peculiar to googleapps? Please show us code actual stacktraces. Python can generate XML just fine, so it's pretty likely that you are doing something wrong. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: strange behaviour of colon within string
On Mon, Oct 19, 2009 at 05:44 -0700, khany wrote: i am relatively new to python and i am trying to convert a php app i have over to it using googleapps. Welcome! anyway here is the problem. i poll ebay API which has in its XML ? xml version=1.0 encoding=utf-8?findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/search/v1/services; however it fails to create the string UNLESS i remove the colon (:) in the http section. i tried to substitute it with chr(58) but it errors the same without showing why. does anyone know what i am doing wrong? is this peculiar to googleapps? Could you please elaborate on fails to create the string, preferably in the form of a traceback. It might also help us if we knew what behaviour you expected or what do you mean by i remove the colon . Wolodja signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
On Oct 19, 10:51 pm, flebber flebber.c...@gmail.com wrote: On Oct 19, 7:40 pm, Javier Santana qualo...@gmail.com wrote: junohttp://github.com/breily/juno it's very easy, uses sqlalchemy as ORM and jinja2 (others can be used if you want) for templates. On Mon, Oct 19, 2009 at 10:24 AM, Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid wrote: flebber a écrit : Hi I have been searching through the vast array of python frameworks http://wiki.python.org/moin/WebFrameworksandits quite astounding the choice available. I am looking at using a web framework for my personal project which isn't actually aimed at developing a website as such. However I deduce that rather than creating a gui application and screen input for data, I can use a web browser for this and have a great array of tools to format input screens and output display formats. Yeps - but remember that a web app will have a couple limitations / drawbacks, specially wrt/ handling complex UI. Since I will be retreiving information from several websites (usually csv files) formatting them and submitting them to a database and creating queries and printouts based on them most frameworks seem to handle this basically with ease and for any complex queries most support SqlAlchemy. Is it simply a case of just picking one and starting and I would find it hard to be dissapointed or is there a few special considerations to make, though I am unsure what they are? Given your specs, forget about monstruosities like Zope, Twisted etc, that will mostly get in the way. You have simple needs, use a simple tool !-) Most obvious ones I am considering are Django (Of course), A pretty good framework, but you'll loose some of it's nice features if you ever want to use an alternate DB layer or templating system. OTHO, most other more flexible frameworks just don't offer this level of integration, so it's may not be such a big deal. Note that Django's ORM, while already pretty good and constently improving, is not as powerful as SLQAlchemy (now nothing prevents you from going down to raw SQL for the more complex queries - and this might be better anyway, since complex queries usually requires to be very fine tuned and tend to not be really portable). The Forms API OTHO is a real winner IMHO. Pylons includes SqlAlchemy, Sql Object and templating and I here turbogears plans to sit on top of this platform. I admit I fail to see what TG brings except for more indirection levels. Zope I am considering but I am a little confused by this. Friendly advice (based on years of working experience): don't waste your time with Zope. The are heaps of others but not sure how to narrow the selection criteria. How/Why woul you split Django and Pylons let alone the others? Django : very strong integration, excellent documentation and support, huge community, really easy to get started with. And possibly a bit more mature and stable... Pylons : more loosely coupled (imply: less integration), based on standard components - which is both a blessing and a curse, specially wrt/ documentation -, requires a good knowledge of Python and the HTTP protocol to get started with. Very powerful and flexible but this comes with a price... Now both are written by talented programmers, and both are pretty good tools. I guess it's more a matter of personal preferences and/or external constraints (PHB etc...) than anything else. A couple other lightweight candidates you migh want to consider are werkzeug and web.py: http://werkzeug.pocoo.org/ http://webpy.org/ Database likely to be MySQl Mmmm If your application is write-heavy, PostgreSQL might be a better choice. Anyway, both Django's ORM and SQLAlchemy work fine with MySQL AFAICT. -- http://mail.python.org/mailman/listinfo/python-list After further reading Django does indeed cover a lot of bases. When looking at jinja2 and werkzueg, first thing I noticed is that they are by the same group called pocoo. Second it shows that I must be misunderstanding something, can I really use jinja2 and sqlAlchemy by itself? The werkzeug documentation shows a screencasthttp://werkzeug.pocoo.org/wiki30/ of making a wiki and uses werkzueg, jinja2 and sqlAlchemy, why werkzueg and jinja2 in combination? And pylons advises use of SqlAlchemy and Mako or choices of Genshi and Jinja2, so what is pylons adding? Might have to do a bit more reading and watch a few more screencasts :-) web2py is interesting the author appears to be implying(I could be misunderstanding this) that the web2py db ORM is equal to if not superior to SQLAlchemy - From http://www.web2py.com/AlterEgo/default/show/150 -- http://mail.python.org/mailman/listinfo/python-list
Re: strange behaviour of colon within string
On 19 Oct, 13:44, khany sharif.k...@gmail.com wrote: hello all, i am relatively new to python and i am trying to convert a php app i have over to it using googleapps. anyway here is the problem. i poll ebay API which has in its XML ? xml version=1.0 encoding=utf-8?findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/search/v1/services; however it fails to create the string UNLESS i remove the colon (:) in the http section. i tried to substitute it with chr(58) but it errors the same without showing why. does anyone know what i am doing wrong? is this peculiar to googleapps? thanks OK first thanks for replying so soon (most other groups out there take days) here is the code xml = '?xml version=1.0 encoding=utf-8? \ findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/ search/v1/services \ categoryId%(category)i/categoryId \ keywords%(searchtext)s/keywords \ paginationInput \ pageNumber%(page)i/pageNumber \ entriesPerPage10/entriesPerPage \ /paginationInput \ /findItemsAdvancedRequest' % \ {'category':9834, 'searchtext':bmw, 'page':1} print xml if i run this, the page is blank (even the source) with no errors or anything. if i remove the colon from the string (after the http) it prints the string on the browser fine. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: strange behaviour of colon within string
On Oct 19, 9:15 pm, khany sharif.k...@gmail.com wrote: On 19 Oct, 13:44, khany sharif.k...@gmail.com wrote: hello all, i am relatively new to python and i am trying to convert a php app i have over to it using googleapps. anyway here is the problem. i poll ebay API which has in its XML ? xml version=1.0 encoding=utf-8?findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/search/v1/services; however it fails to create the string UNLESS i remove the colon (:) in the http section. i tried to substitute it with chr(58) but it errors the same without showing why. does anyone know what i am doing wrong? is this peculiar to googleapps? thanks OK first thanks for replying so soon (most other groups out there take days) here is the code xml = '?xml version=1.0 encoding=utf-8? \ findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/ search/v1/services \ categoryId%(category)i/categoryId \ keywords%(searchtext)s/keywords \ paginationInput \ pageNumber%(page)i/pageNumber \ entriesPerPage10/entriesPerPage \ /paginationInput \ /findItemsAdvancedRequest' % \ {'category':9834, 'searchtext':bmw, 'page':1} print xml if i run this, the page is blank (even the source) with no errors or anything. if i remove the colon from the string (after the http) it prints the string on the browser fine. HTH you can use a tri-quote string or make sure all lines end with \: xml1 = ?xml version=1.0 encoding=utf-8? findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/\ search/v1/services categoryId%(category)i/categoryId keywords%(searchtext)s/keywords paginationInput pageNumber%(page)i/pageNumber entriesPerPage10/entriesPerPage /paginationInput /findItemsAdvancedRequest % \ {'category':9834, 'searchtext':bmw, 'page':1} xml2 = '?xml version=1.0 encoding=utf-8?\n\ findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/\ search/v1/services\n\ categoryId%(category)i/categoryId\n\ keywords%(searchtext)s/keywords\n\ paginationInput\n\ pageNumber%(page)i/pageNumber\n\ entriesPerPage10/entriesPerPage\n\ /paginationInput\n\ /findItemsAdvancedRequest' % \ {'category':9834, 'searchtext':bmw, 'page':1} print xml1 print xml2 -- http://mail.python.org/mailman/listinfo/python-list
Re: File not closed on exception
arve.knud...@gmail.com wrote: Hi I thought that file objects were supposed to be garbage-collected and automatically closed once they go out of scope, at least that's what I've been told by more merited Python programmers. I'm also quite sure that this is quite a common assumption in various programs, at least given what opensource code I've seen in my time. However, the following script doesn't work on Windows, since the file is still open when I try to remove it: import os.path def create(): f = file(tmp, w) raise Exception try: create() finally: os.remove(tmp) So, what's the deal exactly, is the file supposed to be garbage- collected (and closed) at the end of create? Thanks! Arve When an exception is raised, the entire stack frame at that location (which includes local vars) is saved in the exception traceback. Since the objects are still alive, they are not GC'ed. That is why this is better: def create(): f = file(tmp, w) try: do_stuff_that_raises_exception finally: os.remove(tmp) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
Diez B. Roggisch wrote: I don't read that out of the post, and it almost certainly is wrong, at least on a general level. There isn't much above SQLAlchemy regarding flexibility power, so while simple cases might be simpler with other ORMs, they often make more complicated ones impossible. But again, I don't think that's the claim there. Both ORMs and others have been described, by their authors, during the PyCon in March 2009: http://us.pycon.org/2009/conference/schedule/event/60/ By the way, this line in web2py you can access legacy databases if tables have an existing unique auto-increment field id and if this field is used for references is a bit like saying any color you like as long as it's black and it's not a light limitation. There wouldn't be much of an impedence mismatch (*) if a numeric auto-increment primary key was enough for everybody. Sure SQLAlchemy is more complex to master :-/ (*) http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx -- http://mail.python.org/mailman/listinfo/python-list
Re: strange behaviour of colon within string
On 19 Oct, 14:44, StarWing weasley...@sina.com wrote: On Oct 19, 9:15 pm, khany sharif.k...@gmail.com wrote: On 19 Oct, 13:44, khany sharif.k...@gmail.com wrote: hello all, i am relatively new to python and i am trying to convert a php app i have over to it using googleapps. anyway here is the problem. i poll ebay API which has in its XML ? xml version=1.0 encoding=utf-8?findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/search/v1/services; however it fails to create the string UNLESS i remove the colon (:) in the http section. i tried to substitute it with chr(58) but it errors the same without showing why. does anyone know what i am doing wrong? is this peculiar to googleapps? thanks OK first thanks for replying so soon (most other groups out there take days) here is the code xml = '?xml version=1.0 encoding=utf-8? \ findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/ search/v1/services \ categoryId%(category)i/categoryId \ keywords%(searchtext)s/keywords \ paginationInput \ pageNumber%(page)i/pageNumber \ entriesPerPage10/entriesPerPage \ /paginationInput \ /findItemsAdvancedRequest' % \ {'category':9834, 'searchtext':bmw, 'page':1} print xml if i run this, the page is blank (even the source) with no errors or anything. if i remove the colon from the string (after the http) it prints the string on the browser fine. HTH you can use a tri-quote string or make sure all lines end with \: xml1 = ?xml version=1.0 encoding=utf-8? findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/\ search/v1/services categoryId%(category)i/categoryId keywords%(searchtext)s/keywords paginationInput pageNumber%(page)i/pageNumber entriesPerPage10/entriesPerPage /paginationInput /findItemsAdvancedRequest % \ {'category':9834, 'searchtext':bmw, 'page':1} xml2 = '?xml version=1.0 encoding=utf-8?\n\ findItemsAdvancedRequest xmlns=http://www.ebay.com/marketplace/\ search/v1/services\n\ categoryId%(category)i/categoryId\n\ keywords%(searchtext)s/keywords\n\ paginationInput\n\ pageNumber%(page)i/pageNumber\n\ entriesPerPage10/entriesPerPage\n\ /paginationInput\n\ /findItemsAdvancedRequest' % \ {'category':9834, 'searchtext':bmw, 'page':1} print xml1 print xml2 StarWing, The triple String works a treat thanks. Not sure what the colon issue was though. Now im getting Unsupported verb errors but thats an ebay API issue i can work with. Thanks to all for your help khany -- http://mail.python.org/mailman/listinfo/python-list
Re: how to write a unicode string to a file ?
On 17.10.09 08:28, Mark Tolonen wrote: Kee Nethery k...@kagi.com wrote in message news:aaab63c6-6e44-4c07-b119-972d4f49e...@kagi.com... On Oct 16, 2009, at 5:49 PM, Stephen Hansen wrote: On Fri, Oct 16, 2009 at 5:07 PM, Stef Mientki stef.mien...@gmail.com wrote: snip The thing is, I'd be VERY surprised (neigh, shocked!) if Excel can't open a file that is in UTF8-- it just might need to be TOLD that its utf8 when you go and open the file, as UTF8 looks just like ASCII -- until it contains characters that can't be expressed in ASCII. But I don't know what type of file it is you're saving. We found that UTF-16 was required for Excel. It would not do the right thing when presented with UTF-8. Excel seems to expect a UTF-8-encoded BOM (byte order mark) to correctly decide a file is written in UTF-8. This worked for me: f=codecs.open('test.csv','wb','utf-8') f.write(u'\ufeff') # write a BOM f.write(u'马克,testing,123\r\n') f.close() That can also be done with the utf-8-sig codec (which adds a BOM at the start on writing): f = codecs.open('test.csv','wb','utf-8-sig') f.write(u'马克,testing,123\r\n') f.close() See http://docs.python.org/library/codecs.html#module-encodings.utf_8_sig Servus, Walter -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
On Oct 20, 12:32 am, Diez B. Roggisch de...@nospam.web.de wrote: web2py is interesting the author appears to be implying(I could be misunderstanding this) that the web2py db ORM is equal to if not superior to SQLAlchemy - From http://www.web2py.com/AlterEgo/default/show/150 I don't read that out of the post, and it almost certainly is wrong, at least on a general level. There isn't much above SQLAlchemy regarding flexibility power, so while simple cases might be simpler with other ORMs, they often make more complicated ones impossible. But again, I don't think that's the claim there. Diez That sounds fair. Bruno posted earlier Django : very strong integration, excellent documentation and support, huge community, really easy to get started with. And possibly a bit more mature and stable... Pylons : more loosely coupled (imply: less integration), based on standard components - which is both a blessing and a curse, specially wrt/ documentation -, requires a good knowledge of Python and the HTTP protocol to get started with. Very powerful and flexible but this comes with a price... Now both are written by talented programmers, and both are pretty good tools. I guess it's more a matter of personal preferences and/or external constraints (PHB etc...) than anything else. A couple other lightweight candidates you migh want to consider are werkzeug and web.py: http://werkzeug.pocoo.org/ http://webpy.org/ In short it seems to me that Django and Web2py include more magic in assisting oneself to create you web/application, whilst Pylons and Werkzueg leave more control in the users hands hopefully leading to greater expression and power. Pylons recommends SQLALchemy and Mako (offers Genshi and Jinja2) and Werkzueg SQLAlchemy and Jinja2. As I don't have the experience to tell the pro's cons of these two apart, would choosing Pylons based on Documentation be a fair call? -- http://mail.python.org/mailman/listinfo/python-list
Re: File not closed on exception
On 2009-10-19, arve.knud...@gmail.com arve.knud...@gmail.com wrote: I thought that file objects were supposed to be garbage-collected and automatically closed once they go out of scope, At some point after they go out of scope, they will be. Eventually. Exactly when is an implementation detail. at least that's what I've been told by more merited Python programmers. I'm also quite sure that this is quite a common assumption in various programs, If your program relies on the assumption that some particular object will be garbage-collected between points A and B, then that's a bug in your program. If you depend on the fact that some object has been delted, then del it. If you depend on the fact that a file is closed, then close it. at least given what opensource code I've seen in my time. However, the following script doesn't work on Windows, since the file is still open when I try to remove it: import os.path def create(): f = file(tmp, w) raise Exception try: create() finally: os.remove(tmp) So, what's the deal exactly, is the file supposed to be garbage- collected (and closed) at the end of create? Nothing is supposed to be garbage-collected. An object _may_ be garbage collected after some point. -- Grant -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: libmsgque 3.6 with perl support
Dear Users, = ?? I would like to announce libmsgque 3.6 and PLMK 1.1 ?? libmsgque is an infrastructure to write programming language ?? independent software using the : ?? ?? Programming Language Micro Kernel ?? architecture. Never was it so easy to write an application server ?? by your own or to extend your software from local-size to company-size. ?? LibMsgque does now support software written in: ?? ?? C, C++, C#, JAVA, Python, Tcl and ?? ??!! ?? Perl ?? !! ?? available on Unix or Windows OS. ?? Performance is always a story and is measured for every supported ?? language on its own. Read more at: ?? ?? http://libmsgque.sourceforge.net/performance.htm CHANGES ?? - Add new programming language Perl ?? The new language is added if the --enable-perl configure switch is used. ?? Create and Install new perl module Net::Msgque. ?? Use native perl MakeMaker build environment to create Perl-Conform build ?? and perform a Perl-Conform installation. - The dependency for Tcl is now optional ?? The Tcl language is added if the --enable-tcl configure switch is used. ?? Be aware that the test-environment depend on Tcl - Add asynchronous background handler ?? This handler is used to process errors not belonging to a transaction in ?? a centralized manner. The feature was implemented as Interface (C++,Java ?? ,C#) or as configuration option (C,Perl,Python,Tcl). - Add signature based type checking ?? Non-Typed languages without usable class or inheritance type checking now ?? using this feature to create type-save code. This feature is used for Tcl ?? and Perl. - Add new Performance Test environment ?? The new environment using a separated directory performance and does ?? create better results combined with a clearly arranged result-table. Read ?? more in performance/README READ MORE == ?? http://libmsgque.sourceforge.net/ ?? http://sourceforge.net/projects/libmsgque/ AUTHOR === ?? aotto1968 -- http://mail.python.org/mailman/listinfo/python-list
Re: efficient running median
Folks, approximate medians -- would you settle for 49 - 51 % ? -- open up new possibilities, and there's quite a lot of work on that, for huuuge datasets. A class of problems: from a data stream X1 X2 ... you want, every so often, a histogram / quantile summary / distribution estimator such that H approximates the distribution of X, so median of H(t) ~ median of some of X. Some parameters of this class: NH, size of H: 100 = H(p) ~ pth percentile of X A, how often you want H window, drop or age old data runtime, memory of course accuracy -- in theory, in practice A histogram viewer in which you can change buckets, colors, zoom, in REALTIME sounds tantalizing -- fast loop fast algorithm + slow loop. Anyone know of one off-the -shelf, python or anything else ? Refs: Manku et al., Approximate medians in one pass with limited memory, 1998, 10p under http://infolab.stanford.edu/~manku/papers.html nice tree pictures they optimize mem (NH * Nbuf) not runtime, and don't window Suri +, Quantiles on Streams, 2006, 5p, http://www.cs.ucsb.edu/~suri/psdir/ency.pdf ~ 20 refs zzz cheers -- denis -- http://mail.python.org/mailman/listinfo/python-list
Re: help to convert c++ fonction in python
On Mon, Oct 19, 2009 at 2:25 AM, Tim Roberts t...@probo.com wrote: You wrote: For the love of baby kittens, please, please, please tell me that you do not believe this securely encrypts your data. The original poster asked to have two C++ functions converted to Python. That's what I did, using the same names as the original. I neither know nor care how they are used, but let us hope the O.P. understands their limitations. These are roughly as useful as the old ROT13 encoding. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. Apologies, I didn't intend to imply that *you* don't know any better, which I'm sure you do, but rather that the OP probably doesn't. And always apply ROT13 twice for extra security. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib send mail dns resolve problem
En Mon, 19 Oct 2009 05:44:14 -0200, 星星 starstarstar...@gmail.com escribió: my email smtp server hostname can be parsed to 5 ips, for example: ** my email smtp server hostname: email-my.local.com ips through dns parse: 1.1.1.1 1.1.1.12 1.1.13.1 1.1.1.14 1.1.1.15 ** but when i send mail using smtplib, i was always using one ip, no dns re-resolve happened, (for example: only use 1.1.1.12). I checked smtplib src code, but i can't find anything strange; smtplib does not issue a dns query for a MX record, if that is what you were expecting. In fact, the Python standard library does not contain any module for DNS handling. for i in range(1000): server = smtplib.SMTP(host) Here, `host` is used directly -- whatever address gethostbyname returns. If you want load balancing among the 5 addresses above, you'll have to do it yourself: host = random.choice(list_of_addresses) If you don't want to hardcode the addresses, there are a few libraries that perform DNS queries in PyPI. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: print()
Dave Angel wrote: It was intended to be understood, not copied. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
Hello, Just to clarify. I did not make any statement about web2py is superior to SQLAlchemy since that is somewhat subjective. SQLALchemy for example does a much better job at accessing legacy databases. web2py is more limited in that respect and we are working on removing those limitations. I do believe web2py is easier to use than SQLAlchemy, is faster (but yet I do not know SQLAchemy to optimize it properly) and has many features in common with sqlaclhemy including connection pools, joins, left joins, aggregates, nested selects (I do not know SQLAlchemy well enough to know about advanced features that web2py may be missing). The web2py DAL works on Google App Engine while none of the other ORMs do. Massimo -- http://mail.python.org/mailman/listinfo/python-list
Anyone have python 3.1.1 installed on Solaris 10 ? (sparc or x86)
Anyone have python 3.1.1 installed on Solaris 10 ? (sparc or x86) I've tried several times on sparc, I keep getting: gcc -lintl -o python \ Modules/python.o \ libpython3.1.a -lsocket -lnsl -lintl -lrt -ldl -lm Undefined first referenced symbol in file libintl_bind_textdomain_codeset libpython3.1.a(_localemodule.o) libintl_gettext libpython3.1.a(_localemodule.o) libintl_textdomain libpython3.1.a(_localemodule.o) libintl_dcgettext libpython3.1.a(_localemodule.o) libintl_bindtextdomain libpython3.1.a(_localemodule.o) libintl_dgettext libpython3.1.a(_localemodule.o) ld: fatal: Symbol referencing errors. No output written to python collect2: ld returned 1 exit status *** Error code 1 make: Fatal error: Command failed for target `python' Ideas ? (I'm not a c programmerso bear with me ;) ) -- http://mail.python.org/mailman/listinfo/python-list
classes riddle
Can somebody clear this up for me? -- Class B(A): def __init__(self, a) A.__init__(a) self.a = a a = A() ba = B(a) bc = B(a) bd = B(a) -- I'm not sure what A.__init__ here does. I would think its __init__ is designed specifically to run once for any given object.. so i'm not sure what happens. and if A calls self.blah(), which instance of B which overrides blah gets called? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tracking down DLL load errors in Windows ?
Mark Tolonen metolone+gm...@gmail.com said : Yes, welcome to Microsoft's solution to DLL Hell...Side-by-Side DLL Hell. As always, it boils down to a philosophical choice : is it better to suffer through Hell alone, or in bad company ? :-) -- http://mail.python.org/mailman/listinfo/python-list
os.system() question
I'm a python n00b and so pardon me in advance if this is really stupid question. I have my suspicions but why does the following not work the way I'm anticipating it will? (python 2.4.4) import os if (os.system('echo test')): ...print 'success' ... else: ...print 'failed' ... test failed if (os.system('echosadf test')): ...print 'success' ... else: ...print 'failed' ... sh: echosadf: command not found success -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system() question
Bryan Irvine wrote: I'm a python n00b and so pardon me in advance if this is really stupid question. I have my suspicions but why does the following not work the way I'm anticipating it will? (python 2.4.4) import os if (os.system('echo test')): ...print 'success' ... else: ...print 'failed' ... test failed if (os.system('echosadf test')): ...print 'success' ... else: ...print 'failed' ... sh: echosadf: command not found success If I had to guess (which I am, since I'm not looking at the docs), I would say that os.system returns the exit code of whatever it ran, and since the exit code on success is almost always 0, and since 0 means False in Python, you get 'failed' the first time around; likewise, a non-zero exit code usually indicates a problem of some sort, and non-zero is True in Python, hence the 'success' the second time around. I wonder how the docs phrase it? ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system() question
On Mon, Oct 19, 2009 at 11:14 AM, Bryan Irvine sparcta...@gmail.com wrote: I'm a python n00b and so pardon me in advance if this is really stupid question. I have my suspicions but why does the following not work the way I'm anticipating it will? (python 2.4.4) import os if (os.system('echo test')): snip It's best to avoid os.system(). Use the newer `subprocess` module instead: http://docs.python.org/library/subprocess.html Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Mon, Oct 19, 2009 at 1:55 PM, inhahe inh...@gmail.com wrote: On Sat, Oct 10, 2009 at 6:34 PM, Mensanator mensana...@aol.com wrote: On Oct 10, 5:02�pm, kj no.em...@please.post wrote: In 01ccc46d-5ea9-4dfe-ba22-699c6b859...@v36g2000yqv.googlegroups.com Mensanator mensana...@aol.com writes: In fact, if it were up to me, I would have made the fundamental looping construct something like repeat: � � � ... � � � if whatever(): � � � � � �break � � � ... So, the second set of '...' doesn't get executed. When I use while not done: ... if n==1: done = True ... the loop will actually complete (which is what I want) instead of aborting, like yours does. I just don't want the loop to execute again. Of course, this is why you would use while not done instead of while True or repeat in that situation, so i'm not sure what your contention is. Now, if I did a break before writing to the file, I would have to do all kinds of clean-up code outside the loop, code that would be run only if the exit were abnormal. This is why I propose an until keyword. until n == 1: ... i know some people don't like to add keywords unnecessarily, but i really like to be able to express programs in a way that reflects what we actually mean, when there's a simple way this could be provided and it's a common use case. i recognize the problem with my solution is that n might not even be defined until somewhere in the loop after until n == 1 is evaluated. this makes it a little weird, but it's not strictly a problem since the interpreter doesn't actually have to evaluate n == 1 until the tail end of the loop. and made all the other looping constructs as syntatic sugar for this one. Luckily, it's not up to you. condescending and manipulative, as it merely begs the question of luckily for whom -- him, or you kj -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
On Oct 18, 11:54 pm, alex23 wuwe...@gmail.com wrote: ru...@yahoo.com wrote: One, it was suggested without any evidence the the OP was probably asking about homework. My observation over several years is that this group has a very poor record of identifying homework problems. And if someone can conclude that the OPs problem was homework with no evidence, then I can conclude that it wasn't, without evidence, equally validly. I've always seen the accusation of homework problem to be less about homework and more about an attempt to get other people to provide working code. In this case, the absence of evidence (ie posting what code has been tried) _is_ indicative of such problems. I don't share your view. Whether or not a question is a homework problem, and whether or not the questioner has provided some indication he/she has tried to solve it before posting are orthogonal issues, and I have not noticed any strong correlation between them in posts to this group. If you feel a poster is just trying to get you to do their work for them while putting in no effort themselves, you are perfectly free not to respond, or to ask them to demonstrate some effort. I said nothing opposing this. This isn't about being churlish, it's about not being able to identify the experience level at which such posters are operating, about not wasting time providing answers that have already been tried rejected etc etc Again, feel free to ask the OP for whatever information *you* feel *you* need to respond effectively. As for learning better by working it out oneself, that is a myth. MRAB broke the OP's request down into already-understood-by-the-OP operations; being able to extrapolate from that is _essential_ to becoming a programmer. I'm not sure how you think that giving someone an answer will ever help them be able to answer similar questions themselves. The process followed to achieve the solution is what is important here, not the solution itself. Right. But you are concluding that only by figuring out the process by reconstructing it from hints can it be learned. I disagree with that and maintain that you can show someone a solution, and they can figure out quite well, seeing the answer worked out, how to get similar answers in the future. In more detail... [Disclaimer: I know nothing about educational methods beyond what I have experienced -- these are my personal opinions.] There are (at least) two ways to learn something. You can adopt an experiential approach by trying to repeat the discovery of the knowledge (guided by a teacher to avoid wasting time, get past too-hard parts, etc). Another way (probably more common) is to simply have someone tell you the facts and you make the effort to remember them and integrate them with what you already know. The first seems to work well when one is facing a large body of knowledge that one is learning about for the first time, more or less independent of anything else in one's life (e.g. the typical collage course). The second seems to working well when you already have a surrounding knowledge structure to integrate the new information with, for example a specific problem you are trying to solve. I would also imagine that individual people have a bias toward one or the other approaches as well. It seems to me that the conceptual barrier facing the OP was thinking he had to look at each digit of his number separately. The two key bits to getting past that is, consider the number as a string, and (what MRAB said), It's a palindrome if it's [string is] the] same as its reverse. Everything past that are python-specific implementation details, specifically conversion of numbers to strings, the existence of the reversed function, and how to deal with the funky value returned by reversed. My guess was the conceptual barrier was the big one, and although the OP was learning Python, was likely to be able to learn about the parts of Python needed to implement a solution simply by looking at a solution (and reading the docs regarding the bits and pieces, str(), reveresed(), join(), etc) -- no need to jump though a bunch of hoops set up for him by (well- meaning) people copying a pedagogy developed for use in a completely different environment. Again, I am *not* saying my evaluation of the OP's needs is correct, only taking issue with your (and several other's) seeming insistence that *only* the experiential response was appropriate. Repeating what I said in my previous post: Different people have different goals and learning styles. Choice is *good*. Give a programmer a code fragment, and you've helped him for a day. Teach a programmer to code, however... Yes, but be sure you're dealing with a programmer first, and not someone who just wants to use a program to help solve a problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
gslindstrom wrote: On Oct 18, 5:56 pm, Gary Herron gher...@digipen.edu wrote: Benjamin Middaugh wrote: Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. Benjamin This problem (and the OP's previous problem) are probably homework problems. If so, it was unethical for the student to ask for a solution here, and it was careless of several responders to provide a solution. Let's not make the same mistake this time. Gary Herron Could be. Or, like me, they could be working the Project Euler problems. IIRC, many of the solutions involve checking for this type of thing. I'd like to see the OP's work before we give our solutions, though. --greg Absolutely. I have no issues asking for or receiving help for apparently simple problems, but a description of what has been tried, preferably with code snippets and results, should be included with the request. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
The Never-Ending Saga Continues
Hi; Now that we know for sure that my code isn't to blame for not being able to download/access images from MySQL I have contacted my hosting service to see if they will do anything about it. Presuming they won't, I need to find a work-around. What I am looking for is a way to upload data into MySQL *and* simultaneously, in the same form (to make it easy for the user), ftp images into a directory. Any way to do this? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
elementtree examples
The official elementtree docs: http://docs.python.org/library/xml.etree.elementtree.html do not appear to contain examples for each object, interface or function. Where would I find examples that use each elementtree function, interface and object? I assume there is some kind of regression testing that is performed on the Python code base and that the regression testing probably has many many examples. Is there a link in the official documentation to those regression test examples? If not, how do I get a link added to the official docs so that I can view all the examples used to test code changes to the various modules? Kee Nethery -- http://mail.python.org/mailman/listinfo/python-list
Re: Capturing a var from JavaScript
Yeah, I know, but if I use CGI then I have to pass variables in the URL, and I was trying to avoid that. Thanks, V On Mon, Oct 19, 2009 at 12:50 PM, geremy condra debat...@gmail.com wrote: On Mon, Oct 19, 2009 at 11:41 AM, Victor Subervi victorsube...@gmail.com wrote: Hey, that's great! Can do it in python? Fantastic! How? How do I ping the browser and get the screen resolution in python? V One way would be to use CGI, or one of its many derivatives. A better way would be to allow the client to do what the client does best, which is render- ie, use javascript. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: The Never-Ending Saga Continues
On Mon, 19 Oct 2009 11:51:04 -0700, Victor Subervi victorsube...@gmail.com wrote: What I am looking for is a way to upload data into MySQL *and* simultaneously, in the same form (to make it easy for the user), ftp images into a directory. Could you let us know why you want to do this -- what you're trying to achieve with it? -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system() question
On Mon, Oct 19, 2009 at 2:14 PM, Bryan Irvine sparcta...@gmail.com wrote: I'm a python n00b and so pardon me in advance if this is really stupid question. I have my suspicions but why does the following not work the way I'm anticipating it will? (python 2.4.4) import os if (os.system('echo test')): ... print 'success' ... else: ... print 'failed' ... test failed A program returns 0 if it executed successfully, but python interprets 0 to mean false. if (os.system('echosadf test')): ... print 'success' ... else:n ... print 'failed' ... sh: echosadf: command not found success In this case, your program fails so it returns a non-zero exit code (32512) which python interprets to mean true. Just switch the test to if(not os.system(command)) and it will work fine. But you should probably use the newer subprocess module instead. http://docs.python.org/library/os.html#os.system : The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: elementtree examples
Kee Nethery k...@kagi.com writes: do not appear to contain examples for each object, interface or function. Where would I find examples that use each elementtree function, interface and object? effbot.org has a few. -- http://mail.python.org/mailman/listinfo/python-list
a simple unicode question
A trivial one, this is the first time I have to deal with Unicode. I am trying to parse a string s='''48° 13' 16.80 N'''. I know the charset is iso-8859-1. To get the degrees I did encoding='iso-8859-1' q=s.decode(encoding) q.split() [u'48\xc2\xb0', u13', u'16.80', u'N'] r=q.split()[0] int(r[:r.find(unichr(ord('\xc2')))]) 48 Is there a better way of getting the degrees? George -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Testoob 1.15 released
On Oct 14, 5:59 pm, Jorgen Grahn grahn+n...@snipabacken.se wrote: But this sentence on the home page The documentation is sadly outdated, but may be a starting point: made me stop looking. As far as I can tell, you cannot even find out what's so advanced about it (or why advanced is a good thing) without starting to use it. A brief comparison with module unittest (which I am rather unhappy with) would have been nice, too. Those are good points Jorgen, thanks. The briefest summary I would give is: (a) You can run your unittest suites unmodified (so it's easy to try out) (b) The test running options have the potential to whet your appetite: % testoob -h Usage = testoob [options] [test1 [test2 [...]]] examples: testoob - run default set of tests testoob MyTestSuite - run suite 'MyTestSuite' testoob MyTestCase.testSomething - run MyTestCase.testSomething testoob MyTestCase - run all 'test*' test methods in MyTestCase Options === --version show program's version number and exit --help, -hshow this help message and exit --bgcolor=WHENWhat's the background color of the terminal. This is used to determine a readable warning color. Choices are ['auto', 'light', 'dark'], default is 'auto' --color-mode=WHEN When should output be in color? Choices are ['never', 'always', 'auto'], default is 'auto' --glob=PATTERNFiltering glob pattern --html=FILE output results in HTML --immediate, -i Immediate feedback about exceptions --list, -lList the test classes and methods found --list-formatted=FORMATTERLike option '-l', just formatted (e.g. csv). --pbarShow a progress bar --pdf=FILEoutput results in PDF (requires ReportLab) --processes=NUM_PROCESSES Run in multiple processes, use Pyro if available --processes_pyro=NUM_PROCESSES Run in multiple processes, requires Pyro --processes_old=NUM_PROCESSES Run in multiple processes, old implementation --randomize-order Randomize the test order --randomize-seed=SEED Seed for randomizing the test order, implies --randomize-order --regex=REGEX Filtering regular expression --repeat=NUM_TIMESRepeat each test --silent, -s no output to terminal --timed-repeat=SECONDSRepeat each test, for a limited time --time-each-test Report the total time for each test --xml=FILEoutput results in XML --quiet, -q Minimal output --verbose, -v Verbose output --vassert Make asserts verbose --interval=SECONDSAdd interval between tests --timeout=SECONDS Fail test if passes timeout --timeout-with-threads=SECONDS Fail test if passes timeout, implemented with threads --stop-on-failStop tests on first failure --debug Run pdb on tests that fail --threads=NUM_THREADS Run in a threadpool --capture Capture the output of the test, and show it only if test fails --coverage=AMOUNT Test the coverage of the tested code, choices are: ['silent', 'slim', 'normal', 'massive', 'xml'] --test-method-glob=PATTERNCollect test methods based on a glob pattern --test-method-regex=REGEX Collect test methods based on a regular expression --profiler=PROFILER Profile the tests with a profiler, choices are: ['hotshot', 'profile'] --profdata=FILE Target file for profiling information, default is 'testoob.stats' --rerun-on-fail Used with --debug, rerun a failing test when debugging it /Jorgen - orip -- http://mail.python.org/mailman/listinfo/python-list
pylab/matplotlib large plot memory management - bug? or tuning parameter needed?
Summary: It is not straightforward to avoid memory leaks/consumption in pylab. If we define x = arange(1e6) # adjust size to make the increment visible, yet fast enough to plot # then repetition of plot(x,hold=0) # consumes increasing memory according to ubuntu system monitor Details: #versions: ubuntu 9.04 standard (py 2.6.2, ipython 0.91, matplotlib 0.98.5.2) , (results here) #or win32 matplotlib '0.98.3', python 2.5 (similar, although mem usage limits and reuses after 3-4 plot()s First, turn off output caching in ipython because it consumes memory (as it should) ipython -pylab -cs 0 plot(x,hold=0) plot(x,hold=0) plot(x,hold=0) # closing the window doesn't help much, neither does close() or any of the below individually # antidote plot(hold=0); gcf().clf(); close() # first often doesn't help! plot(hold=0); gcf().clf(); close() # need all three! plot(hold=0); gcf().clf(); close() As stated above, the windows version apparently starts more aggressive garbage collection after 3-4 plots. The ubuntu version reaches my system memory limit (1GB) without reclaiming memory - i.e. memory usage just keeps growing until swap space is used when array is 2e6 elements, consuming 100mB per plot. For 1e6 elements, memory usage grows for about 10 50MB steps, and then some garbage collection seems to happen, alothough more can be freeed with the triple line above. 1/ I am running under VMWare so maybe VMWare isn;t reporting the correct physical memory size to ubuntu/python - how to check this? 2/ possible bug - why doesn't closing the plot window release all memory it uses? Especially when this approaches machine memory size. 3/ Are there python/matplotlib memory management tuning parameters I can tweak? -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe and croatian letters
Mark Tolonen wrote: Samir aluko...@work a.dexter...@gmail.com wrote in message news:ab6475d0-133c-478d-8f08-eafea0733...@j39g2000yqh.googlegroups.com... I am making a simple program in Croatian. In the beginning I set # - *- coding: cp1250 -*- code and when i run it in Python shell it comes out fine, but when i compile it with py2exe he doesn't print out croatian letters but he prints out tottaly other letters. I checked the CMD and it supports croatian letters. If you want an source code and setup file send me an e-mail at a.dexter...@gmail.com Not knowing what were considered Croatian characters, I found http://www.geocities.com/click2speak/unicode/chars_hr.html for my testing. Run 'chcp' from CMD and see what code page you are in. I was able to output correctly by changing the codepage from 437 (my U.S. default), to 1250. I also had to change my console window font from 'Raster Fonts' to 'Lucida Console', since the former supported the cp437 character set only. -Mark @mark i checked and he is showing cp852. i'll try to change the cp and then i'll inform you. -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe and croatian letters
Mark Tolonen wrote: Samir aluko...@work a.dexter...@gmail.com wrote in message news:ab6475d0-133c-478d-8f08-eafea0733...@j39g2000yqh.googlegroups.com... I am making a simple program in Croatian. In the beginning I set # - *- coding: cp1250 -*- code and when i run it in Python shell it comes out fine, but when i compile it with py2exe he doesn't print out croatian letters but he prints out tottaly other letters. I checked the CMD and it supports croatian letters. If you want an source code and setup file send me an e-mail at a.dexter...@gmail.com Not knowing what were considered Croatian characters, I found http://www.geocities.com/click2speak/unicode/chars_hr.html for my testing. Run 'chcp' from CMD and see what code page you are in. I was able to output correctly by changing the codepage from 437 (my U.S. default), to 1250. I also had to change my console window font from 'Raster Fonts' to 'Lucida Console', since the former supported the cp437 character set only. -Mark it is working thank you guys -- http://mail.python.org/mailman/listinfo/python-list
Re: a simple unicode question
George Trojan schrieb: A trivial one, this is the first time I have to deal with Unicode. I am trying to parse a string s='''48° 13' 16.80 N'''. I know the charset is iso-8859-1. To get the degrees I did encoding='iso-8859-1' q=s.decode(encoding) q.split() [u'48\xc2\xb0', u13', u'16.80', u'N'] r=q.split()[0] int(r[:r.find(unichr(ord('\xc2')))]) 48 Is there a better way of getting the degrees? Instead of this rather convoluted way to specify a degree-sign, better do # -*- coding: utf-8 -*- ... int(r[:r.find(u°)]) Please note that the utf-8-encoding has *nothing* todo with your string - it's just the source-file encoding. Of course your editor must use utf-8 for saving the encoding. Or you can use any other one you like. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw_input with readline in a daemon thread makes terminal text disappear
In article mailman.1448.1255618675.2807.python-l...@python.org, John O'Hagan resea...@johnohagan.com wrote: I'm getting input for a program while it's running by using raw_input in a loop in separate thread. This works except for the inconvenience of not having a command history or the use of backspace etc. That can be solved by loading the readline module; however, it results in a loss of visible access to the terminal when the program ends: nothing is echoed to the screen and the history is invisible (although it is there - hitting return executes whatever should be there normally). The only way to get it back is to close the terminal and open a new one. Can you restructure your program so that input gets handled in the main thread? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Member of the Groucho Marx Fan Club -- http://mail.python.org/mailman/listinfo/python-list
Re: a simple unicode question
On 19 Okt, 21:07, George Trojan george.tro...@noaa.gov wrote: A trivial one, this is the first time I have to deal with Unicode. I am trying to parse a string s='''48° 13' 16.80 N'''. I know the charset is iso-8859-1. To get the degrees I did encoding='iso-8859-1' q=s.decode(encoding) q.split() [u'48\xc2\xb0', u13', u'16.80', u'N'] r=q.split()[0] int(r[:r.find(unichr(ord('\xc2')))]) 48 Is there a better way of getting the degrees? George When parsing strings, use Regular Expressions. If you don't know how to, spend some time teaching yourself how to - well spent time! A great tool for playing around with REs is KODOS. For the problem at hand you can e.g.: import re degrees = int(re.findall('\d+', s)[0]) that in essence will group together all groups of consecutive digits, return the first group and int() it. No need to care/know about the fact that the string is Unicode and the underlying coding of the charset. -- http://mail.python.org/mailman/listinfo/python-list
Re: elementtree examples
On Oct 19, 2009, at 12:06 PM, Paul Rubin wrote: Kee Nethery k...@kagi.com writes: do not appear to contain examples for each object, interface or function. Where would I find examples that use each elementtree function, interface and object? effbot.org has a few. yes I agree it has a few. It's not anywhere close to complete. I am looking for examples for each object, interface or function. If you just take the very first function in the official docs as an example: xml.etree.ElementTree.Comment([text]) The effbot.org site appears to contain no working examples of that function. At a minimum it would be kind of nice for two simple examples, one with str and one with unicode text showing the XML before and after this function acts upon it. Am looking for that level of documentation for each function, interface and object listed in the official docs for elementtree. Does it exist? Thanks, Kee Nethery -- http://mail.python.org/mailman/listinfo/python-list
Re: classes riddle
inhahe wrote: Can somebody clear this up for me? -- Class B(A): def __init__(self, a) A.__init__(a) self.a = a a = A() ba = B(a) bc = B(a) bd = B(a) -- I'm not sure what A.__init__ here does. I would think its __init__ is designed specifically to run once for any given object.. so i'm not sure what happens. and if A calls self.blah(), which instance of B which overrides blah gets called? This won't run, for a pile of reasons, starting with formatting. Try posting properly indented code, with capitalization correct, and without missing colons. But your first question isn't too hard. The __init__() method of each class runs when an instance (object) of that class is created. But if you inherit from another class, and that class needs arguments, you have to call its __init___() method as well. You use the A. qualifier so that the compiler knows which __init__ method to invoke. Your second question doesn't make sense. A calls self.blah() ?? you seem to be saying that the class calls some method? which instance... gets called ??? Instances don't get called. Perhaps your question is what happens when a method of A calls another method of A, where the same method name occurs (override) in B. The answer to which instance of B is used depends simply on which instance of B was used for the original method call. And in fact which method is called also depends on whether the instance is of type A or type B. Best to give definitions of two classes (with proper indentation), where A has two methods, and B only overrides one of them. Then you can state your question more concretely, or even try it to see. In fact, by the time you spell it out completely, the answer could very well be obvious to you. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: The Never-Ending Saga Continues
Of course. 1) I need to upload data: images and other fields (mainly varchar, int). 2) I want to upload the other fields to a MySQL database. 3) Since it is so problematic, I now want to upload the images to *anything but* a MySQL database (presumably ftp) 4) I want to make this easy (transparent) for my client. Let her just fill out a form and be done with it. TIA, V On Mon, Oct 19, 2009 at 2:58 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: On Mon, 19 Oct 2009 11:51:04 -0700, Victor Subervi victorsube...@gmail.com wrote: What I am looking for is a way to upload data into MySQL *and* simultaneously, in the same form (to make it easy for the user), ftp images into a directory. Could you let us know why you want to do this -- what you're trying to achieve with it? -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
On Oct 19, 12:41 pm, Ethan Furman et...@stoneleaf.us wrote: gslindstrom wrote: On Oct 18, 5:56 pm, Gary Herron gher...@digipen.edu wrote: Benjamin Middaugh wrote: Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. Benjamin This problem (and the OP's previous problem) are probably homework problems. If so, it was unethical for the student to ask for a solution here, and it was careless of several responders to provide a solution. Let's not make the same mistake this time. Gary Herron Could be. Or, like me, they could be working the Project Euler problems. IIRC, many of the solutions involve checking for this type of thing. I'd like to see the OP's work before we give our solutions, though. --greg Absolutely. I have no issues asking for or receiving help for apparently simple problems, but a description of what has been tried, preferably with code snippets and results, should be included with the request. ~Ethan~ I agree such info *should* be included, but if it is relatively clear what the poster is asking about, and I can answer without such info, I will do so (although perhaps while mentioning that the next time including such info would be helpful, if no one else had pointed this out.) People in this group can be pissy enough without my adding to it by insisting a poster jump though some hoops before I'll spend my precious time answering. Another factor is an answer posted here is not only to the benefit of the questioner, but also to the benefit of many other silent readers who shouldn't be penalized due to the faults of the questioner. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Never-Ending Saga Continues
On Mon, 19 Oct 2009 12:56:19 -0700, Victor Subervi victorsube...@gmail.com wrote: Of course. 1) I need to upload data: images and other fields (mainly varchar, int). 2) I want to upload the other fields to a MySQL database. 3) Since it is so problematic, I now want to upload the images to *anything but* a MySQL database (presumably ftp) 4) I want to make this easy (transparent) for my client. Let her just fill out a form and be done with it. How large are the images? If they're not too large, you could use a simple web form to upload everything to a script which then takes care of adding data to the database or filesystem as appropriate -- no need for FTP. On Mon, Oct 19, 2009 at 2:58 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: On Mon, 19 Oct 2009 11:51:04 -0700, Victor Subervi victorsube...@gmail.com wrote: What I am looking for is a way to upload data into MySQL *and* simultaneously, in the same form (to make it easy for the user), ftp images into a directory. Could you let us know why you want to do this -- what you're trying to achieve with it? -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
ru...@yahoo.com wrote: On Oct 19, 12:41 pm, Ethan Furman et...@stoneleaf.us wrote: gslindstrom wrote: On Oct 18, 5:56 pm, Gary Herron gher...@digipen.edu wrote: Benjamin Middaugh wrote: Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. Benjamin This problem (and the OP's previous problem) are probably homework problems. If so, it was unethical for the student to ask for a solution here, and it was careless of several responders to provide a solution. Let's not make the same mistake this time. Gary Herron Could be. Or, like me, they could be working the Project Euler problems. IIRC, many of the solutions involve checking for this type of thing. I'd like to see the OP's work before we give our solutions, though. --greg Absolutely. I have no issues asking for or receiving help for apparently simple problems, but a description of what has been tried, preferably with code snippets and results, should be included with the request. ~Ethan~ I agree such info *should* be included, but if it is relatively clear what the poster is asking about, and I can answer without such info, I will do so (although perhaps while mentioning that the next time including such info would be helpful, if no one else had pointed this out.) People in this group can be pissy enough without my adding to it by insisting a poster jump though some hoops before I'll spend my precious time answering. Another factor is an answer posted here is not only to the benefit of the questioner, but also to the benefit of many other silent readers who shouldn't be penalized due to the faults of the questioner. Your arguments are most persuasive. Consider me convinced. Even if the worst-case scenario is true (homework problem, ack!), either the poster will learn from the answer in which case all is well, or the poster will not, in which case the final exam will show it. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Capturing a var from JavaScript
Victor Subervi wrote: It doesn't work. What I want is to capture winX and winY and use them in python. How? Since you're still not heeding the advice from this article, please allow me to refer you to it again: http://catb.org/~esr/faqs/smart-questions.html -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
ru...@yahoo.com wrote in message news:63dea9e7-97af-4b20-aa0a-c762d9944...@a21g2000yqc.googlegroups.com... On Oct 18, 4:20 pm, MRAB pyt...@mrabarnett.plus.com wrote: Benjamin Middaugh wrote: Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. It's a palindrome if it's the same as its reverse. You already know how to reverse it, and you should already know how to check whether two things are the same, so... :-) Something like: def is_palidrome (n): return str(n) == ''.join (reversed (str(n))) which will return True if integer n is a palidromic or False otherwise. I wouldn't normally provide a direct solution to this type of request; but since you have, may I suggest: def is_palindrome (n): return str(n) == str(n)[::-1] -- http://mail.python.org/mailman/listinfo/python-list
Passing a sqlite connection into an extension module
Hello- I'm trying to find out if there is a way to share a sqlite database connection between python and an extension module written in C or C+ +. My setup is that I have some pretty intensive OpenGL rendering code that gets its values from a largish sqlite database, performs a fair bit of computation, and then draws. I'm throwing everything I can at it to keep the code in python (numpy, Cython, vertex arrays and drawlists), but the initial rendering is very slow, and it's fast becoming much more time consuming for me to optimize the python than it would be to write equivalent code in a C++ extension module. However, I would like to have access to the same database from within Python for running lesser queries, and for prototyping new features. The problem is that I may be running from an in-memory database, and I might also be using temporary tables (for a cache), which are not shared across separate connections. I would like to grab the pointer to the sqlite3 connection struct, and pass it to an extension module so that I can use sqlite's native API. I can not find any way to do such a thing in either the standard sqlite module, or in APSW. Has anyone had any experience with this? I can think of some workarounds (such as hack APSW, among other ideas). Any caveats? Thanks, -matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
On Sun, 18 Oct 2009 23:04:36 -0700 (PDT), alex23 wuwe...@gmail.com wrote: On Oct 19, 3:53 pm, Jabba Laci jabba.l...@gmail.com wrote: Would someone explain how str[::-1] work? I'm new to Python and I only saw so far the str[begin:end] notation. What is the second colon? Slice notation is of the form [start:stop:step]. start defaults to the start of the sequence, stop to the end, and step to 1. So a slice of [::-1] returns the full sequence in reverse, stepping back one character at a time from the end of the sequence to the beginning. The only mention I could find was http://docs.python.org/dev/3.0/library/functions.html#slice There's also http://docs.python.org/reference/datamodel.html#index-791 Martien -- | Martien Verbruggen | There are only 10 types of people in first.l...@heliotrope.com.au | the world; those who understand binary | and those who don't. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Never-Ending Saga Continues
Can you give me an example of this? V On Mon, Oct 19, 2009 at 4:03 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: On Mon, 19 Oct 2009 12:56:19 -0700, Victor Subervi victorsube...@gmail.com wrote: Of course. 1) I need to upload data: images and other fields (mainly varchar, int). 2) I want to upload the other fields to a MySQL database. 3) Since it is so problematic, I now want to upload the images to *anything but* a MySQL database (presumably ftp) 4) I want to make this easy (transparent) for my client. Let her just fill out a form and be done with it. How large are the images? If they're not too large, you could use a simple web form to upload everything to a script which then takes care of adding data to the database or filesystem as appropriate -- no need for FTP. On Mon, Oct 19, 2009 at 2:58 PM, Rami Chowdhury rami.chowdh...@gmail.com wrote: On Mon, 19 Oct 2009 11:51:04 -0700, Victor Subervi victorsube...@gmail.com wrote: What I am looking for is a way to upload data into MySQL *and* simultaneously, in the same form (to make it easy for the user), ftp images into a directory. Could you let us know why you want to do this -- what you're trying to achieve with it? -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
On Oct 18, 4:56 pm, Gary Herron gher...@digipen.edu wrote: Benjamin Middaugh wrote: Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. Benjamin This problem (and the OP's previous problem) are probably homework problems. If so, it was unethical for the student to ask for a solution here, and it was careless of several responders to provide a solution. Let's not make the same mistake this time. You think that was homework? Perhaps so but for the record here are some posts by some other people who suspected homework in the very recent past... 2009-10-03 http://groups.google.com/group/comp.lang.python/browse_frm/thread/a032adcdcaff7d9/0e74d426d30170e9?lnk=gstq=homework#0e74d426d30170e9 Chris Rebert wrote: Since this sounds like homework, skorpi...@gmail.com wrote: Thanks Chris, Not homework but self learning. 2009-10-01 http://groups.google.com/group/comp.lang.python/browse_frm/thread/f70457535a7c252e/e785984ffc1dc5c3?lnk=gstq=homework#e785984ffc1dc5c3 Laszlo Nagy wrote: Is this a homework? kj wrote: Earlier some other clown alleged that that my original post was homework??? WTF? 2009-09-27 http://groups.google.com/group/comp.lang.python/browse_frm/thread/a032adcdcaff7d9/0e74d426d30170e9?lnk=gstq=homework#0e74d426d30170e9 John Nagle wrote This looks like a homework assignment. dads wrote: No this certainly isn't homework, I'm 29 and in full time work. -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
Django : very strong integration, excellent documentation and support, huge community, really easy to get started with. And possibly a bit more mature and stable... One strong point in favour of Django: it follows Python's philosophy of batteries included, and features a large array of plugins. There are also numerous other add-ons created by the community. Also, it has a pretty great administration interface. It still manages to retain flexibility, but you're basically stuck with Django's ORM (which is OK for simple things) and templating language (which is OK as long as you don't need custom tags). Pylons : more loosely coupled (imply: less integration), based on standard components - which is both a blessing and a curse, specially wrt/ documentation -, requires a good knowledge of Python and the HTTP protocol to get started with. Very powerful and flexible but this comes with a price... Haven't used Pylons, but the documentation has improved the last few years with the Pylons book (http://pylonsbook.com/en/1.0/), while still not being up to par with Django's. It has also a methodology for deployment, which Django decidedly lacks. Cheers, Emm -- http://mail.python.org/mailman/listinfo/python-list
Re: The Never-Ending Saga Continues
On Mon, 19 Oct 2009 14:20:38 -0700, Victor Subervi victorsube...@gmail.com wrote: Can you give me an example of this? V An example of an online upload form? Sure -- Gmail's Basic HTML interface for attachments is a good example. I'd advise doing a web search or two for HTTP file uploads, multipart forms, and so on. Just a tip with regarding to posting to this and other lists -- if you put your response *below* the quoted text that you are replying to, it helps people understand the conversation, and doesn't force them to scroll down and try to figure out who said what when (which can be a bit frustrating). On Mon, Oct 19, 2009 at 4:03 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: On Mon, 19 Oct 2009 12:56:19 -0700, Victor Subervi victorsube...@gmail.com wrote: Of course. 1) I need to upload data: images and other fields (mainly varchar, int). 2) I want to upload the other fields to a MySQL database. 3) Since it is so problematic, I now want to upload the images to *anything but* a MySQL database (presumably ftp) 4) I want to make this easy (transparent) for my client. Let her just fill out a form and be done with it. How large are the images? If they're not too large, you could use a simple web form to upload everything to a script which then takes care of adding data to the database or filesystem as appropriate -- no need for FTP. On Mon, Oct 19, 2009 at 2:58 PM, Rami Chowdhury rami.chowdh...@gmail.com wrote: On Mon, 19 Oct 2009 11:51:04 -0700, Victor Subervi victorsube...@gmail.com wrote: What I am looking for is a way to upload data into MySQL *and* simultaneously, in the same form (to make it easy for the user), ftp images into a directory. Could you let us know why you want to do this -- what you're trying to achieve with it? -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
smtplib upload progress
Hi, I wanted to use smtplib to send a bunch of files. All good, except I cant monitor the upload progress as far as I can see. So I monkey patched the SMTP.sendall method, which chops up the data and keeps calling a provided callback for every chunk of data sent. This feels kind of dirty and I was wondering what my other options are to tackle this seemingly simple problem. thanx, Guyon Moree -- http://mail.python.org/mailman/listinfo/python-list
os.path.join
Following closely on the heels of the whole sum()ing strings debate, I think I found an error -- at least, it's not documented to behave this way... def uncompress_job(job_num, save_path='z:\\old_jobs', restore_path='z:\\orders'): destination = os.path.join([restore_path, job_num]) print os.path.join([save_path, job_num]) As the astute reader will doubt notice, job_num should be a string. As I was not an astute typer during development, I just put in an integer: --uncompress_job(18273) ['z:\\oldjobs', 19858] I did have more interesting errors to lead me to this point, but here I am, and my question... shouldn't os.path.join raise an exception if an incompatible type is passed to it? I sure wish it had! ;-) I was expecting, and the documentation led me to believe, that a string would be returned, not a list. ~Ethan~ -- Documentation -- join( path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted between components, unless path2 is empty. Note that on Windows, since there is a current directory for each drive, os.path.join(c:, foo) represents a path relative to the current directory on drive C: (c:foo), not c:\\foo. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join
Ethan Furman wrote: Following closely on the heels of the whole sum()ing strings debate, I think I found an error -- at least, it's not documented to behave this way... def uncompress_job(job_num, save_path='z:\\old_jobs', restore_path='z:\\orders'): destination = os.path.join([restore_path, job_num]) print os.path.join([save_path, job_num]) As the astute reader will doubt notice, job_num should be a string. As I was not an astute typer during development, I just put in an integer: --uncompress_job(18273) ['z:\\oldjobs', 19858] I did have more interesting errors to lead me to this point, but here I am, and my question... shouldn't os.path.join raise an exception if an incompatible type is passed to it? I sure wish it had! ;-) I was expecting, and the documentation led me to believe, that a string would be returned, not a list. ~Ethan~ -- Documentation -- join( path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted between components, unless path2 is empty. Note that on Windows, since there is a current directory for each drive, os.path.join(c:, foo) represents a path relative to the current directory on drive C: (c:foo), not c:\\foo. *AHhh* I am _so_ embarrassed. Looks like I was supposed to pass individual items, not a single list. Going to the code, I found this: ntpath.py - def join(a, *p): Join two or more pathname components, inserting \\ as needed path = a for b in p: . . . return path and because there was nothing for *p, I just got back what I gave it. GIGO is alive and well! ;-) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
def is_palidrome (n): return str(n) == ''.join (reversed (str(n))) which will return True if integer n is a palidromic or False otherwise. I wouldn't normally provide a direct solution to this type of request; but since you have, may I suggest: def is_palindrome (n): return str(n) == str(n)[::-1] http://gumuz.nl/weblog/python-trick-sequence-reversal/ -- http://mail.python.org/mailman/listinfo/python-list
Re: elementtree examples
On Oct 19, 2009, at 1:02 PM, Robert Kern wrote: On 2009-10-19 14:50 PM, Kee Nethery wrote: Am looking for that level of documentation for each function, interface and object listed in the official docs for elementtree. Does it exist? No. Thank you. Kee -- http://mail.python.org/mailman/listinfo/python-list
Request for Beta Testers
Hello, My company is seeking beta testers for a new cloud-computing platform that is built for the Python programming language. The platform allows Python developers to leverage the computational power of a cluster of servers with only a couple lines of code. If you have a need for distributed computing, or just want to try out some cutting-edge technology, please reply. We'll be letting the first 30 respondents into our closed beta. Common use cases for our platform: * Crawling the web * Manipulating images and videos * Creating charts and graphs * Statistical/Mathematical analysis of data sets * Real-time data processing Best, Ken Elkabany -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
On Oct 20, 3:31 am, Massimo Di Pierro mdipie...@cs.depaul.edu wrote: Hello, Just to clarify. I did not make any statement about web2py is superior to SQLAlchemy since that is somewhat subjective. SQLALchemy for example does a much better job at accessing legacy databases. web2py is more limited in that respect and we are working on removing those limitations. I do believe web2py is easier to use than SQLAlchemy, is faster (but yet I do not know SQLAchemy to optimize it properly) and has many features in common with sqlaclhemy including connection pools, joins, left joins, aggregates, nested selects (I do not know SQLAlchemy well enough to know about advanced features that web2py may be missing). The web2py DAL works on Google App Engine while none of the other ORMs do. Massimo So does web2py allow for raw sql if there is an advanced procedure or query that needs to be performed that is outside the scope of the web2pr orm -- http://mail.python.org/mailman/listinfo/python-list
Is __mul__ sufficient for operator '*'?
Hi everyone, I was having a go at a simple implementation of Maybe in Python when I stumbled on a case where x.__mul__(y) is defined while x*y is not. The class defining x is: class Maybe(object): def __init__(self, obj): self.o = obj def __repr__(self): return 'Maybe(%s)' % object.__getattribute__(self, o) def __getattribute__(self, name): try: o = object.__getattribute__(self, o) r = getattr(o,name) if callable(r): f = lambda *x:Maybe(r(*x)) return f else: return Maybe(r) except: return Maybe(None) The code exercising this class is: x=Maybe(9) x.__mul__(7) Maybe(63) x*7 Traceback (most recent call last): File pyshell#83, line 1, in module x*7 TypeError: unsupported operand type(s) for *: 'Maybe' and 'int' The farthest I can go in this is that I presume that __mul__ (as called by operator *) is supposed to be a bound method while I am returning a lambda function. Is this correct? And How can I make the implementation support such operators? Cheers, Muhammad Alkarouri -- http://mail.python.org/mailman/listinfo/python-list
Re: organizing your scripts, with plenty of re-use
On Oct 15, 4:30 pm, bukzor workithar...@gmail.com wrote: On Oct 13, 3:20 pm, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Tue, 13 Oct 2009 17:38:44 -0300, Buck workithar...@gmail.com escribió: The only way to get your packages on the PYTHONPATH currently is to: * install the packages to site-packages (I don't have access) * edit the PYTHONPATH all users' environment (again, no access) * create some boilerplate that edits sys.path at runtime (various problems in previous post) * put your scripts directly above the package (this seems best so far, but forces a flat hierarchy of scripts) Not exactly - in short, you have to place the package under some directory that is eventually listed in sys.path. By default, one of such directories is site-packages, but there are also per-user directories. On Windows, %APPDATA%\Python\PythonNN\site-packages (see PEP 370 [1]). If you don't want to copy the package there, you can even add a .pth file and it will be processed. The .pth files are intriguing. Is this the best reference?http://docs.python.org/library/site.html My current solution very closely resembles the .pth system, but uses the scripts' directory and accepts relative paths. If I'm reading the doc correctly, the .pth system currently doesn't support either of these. Does anyone know of the rationale for this? I thought this was one of the least objectionable of my posts. Does anyone know how to find a discussion of the .pth implementation? -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
web2py is interesting the author appears to be implying(I could be misunderstanding this) that the web2py db ORM is equal to if not superior to SQLAlchemy - From http://www.web2py.com/AlterEgo/default/show/150 I don't read that out of the post, and it almost certainly is wrong, at least on a general level. There isn't much above SQLAlchemy regarding flexibility power, so while simple cases might be simpler with other ORMs, they often make more complicated ones impossible. But again, I don't think that's the claim there. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: help to convert c++ fonction in python
On Sat, 17 Oct 2009 19:48:46 -0400, geremy condra wrote: For the love of baby kittens, please, please, please tell me that you do not believe this securely encrypts your data. Surely that depends on your threat model? If you think that the NSA is interested in your data, then no, obviously they'll break it in probably minutes. If you're using it to obfuscate (say) dialog strings in a game, so that game players can't trivially open the data files in an editor and read ahead, then this may be enough security against your threat model, so the answer may be Yes. But that depends on the game -- if there is real money involved, then probably No. Secure is not a binary state. It's always secure against what?. You might have the latest, most powerful encryption software, but what are you going to do if the authorities hit your hand with a hammer until you give up the passphrase? (Figuratively or literally.) If you live in a country where this is a risk, then your threat model is different and AES, 3DES or other standard cryptosystems won't make you any more secure than rot13. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Is __mul__ sufficient for operator '*'?
Muhammad Alkarouri wrote: Hi everyone, I was having a go at a simple implementation of Maybe in Python when I stumbled on a case where x.__mul__(y) is defined while x*y is not. The class defining x is: class Maybe(object): def __init__(self, obj): self.o = obj def __repr__(self): return 'Maybe(%s)' % object.__getattribute__(self, o) def __getattribute__(self, name): try: o = object.__getattribute__(self, o) r = getattr(o,name) if callable(r): f = lambda *x:Maybe(r(*x)) return f else: return Maybe(r) except: return Maybe(None) The code exercising this class is: x=Maybe(9) x.__mul__(7) Maybe(63) x*7 Traceback (most recent call last): File pyshell#83, line 1, in module x*7 TypeError: unsupported operand type(s) for *: 'Maybe' and 'int' The product 7*x will execute __mul__, but to catch x*7, you need to define __rmul__ (the 'r' stands for reverse or some such). However, in fact, you have *not* defined __mul__ in your class. Your __getattribute__ is catching __mul__ as an undefined reference, and doing something with it -- not sure what though. As proof, continue testing: x.__mul__ and x.__rmul__ both return values (lambdas defined within __getattribute__) and neither x*7 or 7*x work. If you want both x* and 7*x to be defined, try def __mul__(self,r): ... def __rmul__(self,r): Or the operation is commutative, perhaps you can get away with reusing __mul__ for both. def __mul__(self,r): ... __rmul__ = __mull__ Gary Herron The farthest I can go in this is that I presume that __mul__ (as called by operator *) is supposed to be a bound method while I am returning a lambda function. Is this correct? And How can I make the implementation support such operators? Cheers, Muhammad Alkarouri -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
En Sun, 18 Oct 2009 21:50:55 -0300, Carl Banks pavlovevide...@gmail.com escribió: Consider this thought experiment: class Something(object): def __radd__(self,other): return other + q x = [a,b,c,Something()] If x were passed to .join(), it would throw an exception; but if passed to a sum() without any special casing, it would successfully return abcq. Thus there is divergence in the two behaviors, thus transparently calling .join() to perform the summation is a Bad Thing Indeed, a much worse special-case behavior than throwing an exception. Just for completeness, and in case anyone would like to try this O(n²) process, sum(x) may be rewritten as: x = [a,b,c,Something()] print reduce(operator.add, x) which does exactly the same thing, with the same quadratic behavior as sum(), but prints abcq as expected. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib send mail dns resolve problem
On 10月19日, 下午11时05分, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Mon, 19 Oct 2009 05:44:14 -0200, 星星 starstarstar...@gmail.com escribió: my email smtp server hostname can be parsed to 5 ips, for example: ** my email smtp server hostname: email-my.local.com ips through dns parse: 1.1.1.1 1.1.1.12 1.1.13.1 1.1.1.14 1.1.1.15 ** but when i send mail using smtplib, i was always using one ip, no dns re-resolve happened, (for example: only use 1.1.1.12). I checked smtplib src code, but i can't find anything strange; smtplib does not issue a dns query for a MX record, if that is what you were expecting. In fact, the Python standard library does not contain any module for DNS handling. for i in range(1000): server = smtplib.SMTP(host) Here, `host` is used directly -- whatever address gethostbyname returns. If you want load balancing among the 5 addresses above, you'll have to do it yourself: host = random.choice(list_of_addresses) If you don't want to hardcode the addresses, there are a few libraries that perform DNS queries in PyPI. -- Gabriel Genellina thanks very much! I tried your suggestion and it worked! But I still wonder why gethostbyname returns the same address all the time(maybe 5 times). -- http://mail.python.org/mailman/listinfo/python-list
Re: elementtree examples
En Mon, 19 Oct 2009 17:02:44 -0300, Robert Kern robert.k...@gmail.com escribió: On 2009-10-19 14:50 PM, Kee Nethery wrote: Am looking for that level of documentation for each function, interface and object listed in the official docs for elementtree. Does it exist? No. Well, not so detailed, but the selftest.py module in the source package for elementtree (available from www.effbot.org) does provide quite a few examples using doctest. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: The Never-Ending Saga Continues
Victor Subervi wrote: Can you give me an example of this? That depends. How much of your client's money are you offering us for doing your work? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib upload progress
En Mon, 19 Oct 2009 19:33:50 -0300, Guyon Morée guyon.mo...@gmail.com escribió: I wanted to use smtplib to send a bunch of files. All good, except I cant monitor the upload progress as far as I can see. So I monkey patched the SMTP.sendall method, which chops up the data and keeps calling a provided callback for every chunk of data sent. This feels kind of dirty and I was wondering what my other options are to tackle this seemingly simple problem. (there is no sendall method in SMTP, but send) Looks like there is no other way... perhaps I'd have overriden data() instead of send(), but it's as dirty as yours, one has to duplicate the original code. I don't know how often the need arises or how useful would this be to others, but you could submit a patch to http://bugs.python.org/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Is __mul__ sufficient for operator '*'?
En Mon, 19 Oct 2009 21:31:44 -0300, Muhammad Alkarouri malkaro...@gmail.com escribió: I was having a go at a simple implementation of Maybe in Python when I stumbled on a case where x.__mul__(y) is defined while x*y is not. __special__ methods are searched in the type, not in the instance directly. x*y looks for type(x).__mul__ (among other things) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Is __mul__ sufficient for operator '*'?
Muhammad Alkarouri schrieb: Traceback (most recent call last): File pyshell#83, line 1, in module x*7 TypeError: unsupported operand type(s) for *: 'Maybe' and 'int' The farthest I can go in this is that I presume that __mul__ (as called by operator *) is supposed to be a bound method while I am returning a lambda function. Is this correct? And How can I make the implementation support such operators? It does not so much depend on the function being bound, but on the fact that Python expects Maybe.__mul__ to be present already when it tries to execute '*'. You could always add this, though: def __mul__(self, other): return Maybe.__getattribute__(self, __mul__)(other) but of course you'd have to do it for every operator you want to use on your Maybe objects. Your use of __getattribute__ OTH suggests you're trying to avoid exactly that. I'd rather go for a monadic implementation with unit, bind and lift operations, e.g: 88888 class Monad(object): # unit: def __init__(self, value): self.value = value # bind: def __rshift__(self, function): return function(self.__class__)(self.value) def __str__(self): return %s(%s) % (self.__class__.__name__, self.value) def lift(f): def lift_unit(m): def lift_bind(x): return m(f(x)) return lift_bind return lift_unit class idem(Monad): def __call__(self, value): return value class Nothing(object): def __rshift__(self, function): return Nothing def __str__(self): return Nothing Nothing = Nothing() class Maybe(Monad): def __new__(cls, value=Nothing): if value is Nothing: return Nothing return super(Monad, cls).__new__(cls) if __name__ == __main__: x = Maybe(9) print x lift(lambda v: v * 7) print x lift(lambda v: v * 7) idem y = Maybe(Nothing) print y lift(lambda v: v * 7) print y lift(lambda v: v * 7) idem 88888 While I can see how this monadic stuff is usefull in Haskell et al., I'm still not sure how to apply it to Python. And for the impenetrable mathematical language in which Monads are usually presented, well... HTH, Mick. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is __mul__ sufficient for operator '*'?
Gabriel Genellina schrieb: __special__ methods are searched in the type, not in the instance directly. x*y looks for type(x).__mul__ (among other things) So I thought too, but: class meta(type): def __mul__(*args): return 123 class boo(object): __metaclass__ = meta print boo.__mul__ b = boo() print b * 7 also explodes. Or am I misinterpreting the word type here? Mick. -- http://mail.python.org/mailman/listinfo/python-list
Re: a simple unicode question
George Trojan george.tro...@noaa.gov wrote in message news:hbidd7$i9...@news.nems.noaa.gov... A trivial one, this is the first time I have to deal with Unicode. I am trying to parse a string s='''48° 13' 16.80 N'''. I know the charset is iso-8859-1. To get the degrees I did encoding='iso-8859-1' q=s.decode(encoding) q.split() [u'48\xc2\xb0', u13', u'16.80', u'N'] r=q.split()[0] int(r[:r.find(unichr(ord('\xc2')))]) 48 Is there a better way of getting the degrees? It seems your string is UTF-8. \xc2\xb0 is UTF-8 for DEGREE SIGN: -- http://mail.python.org/mailman/listinfo/python-list
Re: a simple unicode question
George Trojan george.tro...@noaa.gov wrote in message news:hbidd7$i9...@news.nems.noaa.gov... A trivial one, this is the first time I have to deal with Unicode. I am trying to parse a string s='''48° 13' 16.80 N'''. I know the charset is iso-8859-1. To get the degrees I did encoding='iso-8859-1' q=s.decode(encoding) q.split() [u'48\xc2\xb0', u13', u'16.80', u'N'] r=q.split()[0] int(r[:r.find(unichr(ord('\xc2')))]) 48 Is there a better way of getting the degrees? It seems your string is UTF-8. \xc2\xb0 is UTF-8 for DEGREE SIGN. If you type non-ASCII characters in source code, make sure to declare the encoding the file is *actually* saved in: # coding: utf-8 s = '''48° 13' 16.80 N''' q = s.decode('utf-8') # next line equivalent to previous two q = u'''48° 13' 16.80 N''' # couple ways to find the degrees print int(q[:q.find(u'°')]) import re print re.search(ur'(\d+)°',q).group(1) -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib connection fails with multiple nics
Sean DiZazzo half.ital...@gmail.com writes: On Oct 16, 4:51 pm, Sean DiZazzo half.ital...@gmail.com wrote: Hi all, I'm trying to connect to an ftp site from a windows machine with two nics going to two different networks, but I keep getting the below exception: Traceback (most recent call last): File ftp.pyo, line 70, in connect File ftp.pyo, line 17, in __init__ File ftplib.pyo, line 131, in connect File socket.pyo, line 498, in create_connection gaierror: [Errno 10093] getaddrinfo failed I think it is because of the two nics, because the code runs fine on other machines. Any ideas on how to fix this? TIA. ~Sean What does socket.getaddrinfo() rely on?? First, check if you can ping the FTP server from your client machine. getaddrinfo relies on either DNS, /etc/hosts, or NIS, depending on how your system is configured (check the hosts entry in /etc/nsswitch.conf). -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib connection fails with multiple nics
Sean DiZazzo half.ital...@gmail.com wrote: I'm trying to connect to an ftp site from a windows machine with two nics going to two different networks, but I keep getting the below exception: Traceback (most recent call last): File ftp.pyo, line 70, in connect File ftp.pyo, line 17, in __init__ File ftplib.pyo, line 131, in connect File socket.pyo, line 498, in create_connection gaierror: [Errno 10093] getaddrinfo failed I think it is because of the two nics, because the code runs fine on other machines. Any ideas on how to fix this? 10093 is WSANOTINITIALISED, implying that WSAStartup has not been called. Are you doing this in a thread? Are these all the same version of the operating system? -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
For me, it's more a question of clarity than anything else. I don't like very much using break, continue or more than one return per function on C/C++, but sometimes it's much clearer to use them. Also, in Python I use them often, as usually the code is cleaner this way. for example, I will wrote that code in C/C++ for (i=0;(iMAX) (get_out == True);i++) { . do lot of things... if( condition) { get_out = True } } but in Python will use for i in range(MAX): ..do lot of things... if condition: #Exit the loop break Don't know, seems to me that the more syntetic code of Python helps me to see clearly when to exit, in C/C++ the break statements seems to confuse me. Probably related with the amount (and density) of code I think an infinity loop (while True:) should be used only on, well, infinite loops (or at least indeterminate ones that depends on arguably input, like user input or network data) I wouldn't use them for reading a file, for example... But, anyway, I think the key concept is to use them when it's more readable and makes more sense than a finite loop. By the way, more readable to me, of course :-P -- http://mail.python.org/mailman/listinfo/python-list