Re: reading files into dicts
ConfigObj is good - it (effectively) turns a dictionary into an ini file, and vice versa. There is also built in support for type conversion. See http://www.voidspace.org.uk/python/configobj.html See the ConfigPersist module which has functions to use ConfigObj for data persistence. It explains the limitations. http://www.voidspace.org.uk/python/configpersist.html Basically you can store and retrieve dictionaries, lists, strings, integers, floats and booleans. You can nest dictionaries - but you can't nest dictionaries in lists. All the keys must be strings - but the module/article suggests a way round that, at the expense of readability of the resulting text file. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Application Portability?
I *think* that Python for the Palm platform is stalled a bit (Pippy). PythonCE is alive and well. Tkinter works quite well as a GUI front end - but you have to work quite hard to build a usable GUI on a PocketPC screen. For a list of resources see http://www.traybor.com/PythonCE/ Luke Dunstan has *just* ported CTypes to the Windows Mobile platform (and I think there is already a win32gui module anyway). This means it ought to be possible to create a GUI using the native win32 widgets. The latest version of Python on the windows CE platform is 2.3.4 - although there are rumblings of a 2.4.2 port. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Python 2.4.2 gcc 3.4.4 Solaris 8 build issues
Hi, I encountered some build issues when compiling Python 2.4.4 on a Solaris 8 box using gcc 3.4.4: 1. Running configure detects that a C++-built main needs C++-linking. Therefore, Python gets linked with g++, creating a dependency on libstdc++. Some research showed up a rather elaborate discussion in the python-dev/c++-sig-archives, ending up in a patch that replaces the --with-cxx option with a --with-cxx-main switch and tries to set CXX to some sensible value in the generated Makefile even if Python gets built C-only. (SF #1324762 Compiling and linking main() with C++ compiler, by Christoph Ludwig; pending) Now, I am still not 100 % sure about what I need to do. I need C++-extensions, but I do not want to link anything statically with Python, i.e. everything will be dynamically imported extension modules. I *think* I can build Python C-only, avoiding possible runtime problems with C++-extensions that might have been built with different C++ compilers. Can anyony clear that up? 2. We have some stuff in non-standard locations here. To build properly, I need to tell this to configure (using CXX, CPPFLAGS, LD_LIBRARY_PATH). Unfortunately, none of this gets communicated to the setup.py step with its find_library_file() stuff, so it is also necessary to either modify setup.py or add a setup.cfg file. Is there some better way to do that? (Probably the Makefile template could be changed to supply setup.py with some appropriate command line options for build_ext, but I do not know the autotools stuff. Any recommendations for some good tutorial?) 3. The test_locale test fails: ./python Lib/test/test_locale.py '%f' % 1024 =? '1,024.00' ... no '%f' % 1024 == '1024.00' != '1,024.00' '%f' % 102 =? '102.00' ... yes '%f' % -42 =? '-42.00' ... yes '%+f' % -42 =? '-42.00' ... yes '%20.f' % -42 =? ' -42' ... yes '%+10.f' % -4200 =? '-4,200' ... no '%+10.f' % -4200 == '-4200' != '-4,200' '%-10.f' % 4200 =? '4,200 ' ... no '%-10.f' % 4200 == '4200 ' != '4,200 ' ' '.isspace() =? True ... yes '\xa0'.isspace() =? False ... no '\xa0'.isspace() == True != False '\xa1'.isspace() =? False ... yes '\xc0'.isalpha() =? False ... no '\xc0'.isalpha() == True != False '\xc0'.isalnum() =? False ... no '\xc0'.isalnum() == True != False '\xc0'.isupper() =? False ... no '\xc0'.isupper() == True != False '\xc0'.islower() =? False ... yes '\xec\xa0\xbc'.split() =? ['\xec\xa0\xbc'] ... no '\xec\xa0\xbc'.split() == ['\xec', '\xbc'] != ['\xec\xa0\xbc'] '\xed\x95\xa0'.strip() =? '\xed\x95\xa0' ... no '\xed\x95\xa0'.strip() == '\xed\x95' != '\xed\x95\xa0' '\xcc\x85'.lower() =? '\xcc\x85' ... no '\xcc\x85'.lower() == '\xec\x85' != '\xcc\x85' '\xed\x95\xa0'.upper() =? '\xed\x95\xa0' ... no '\xed\x95\xa0'.upper() == '\xcd\x95\xa0' != '\xed\x95\xa0' ?? Is this a known problem on Solaris? Thanks in advance for any hints, Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empfänger sind oder falls diese E-Mail irrtümlich an Sie adressiert wurde, verständigen Sie bitte den Absender sofort und löschen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte Übermittlung sind nicht gestattet. Die Sicherheit von Übermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Bestätigung wünschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. -- http://mail.python.org/mailman/listinfo/python-list
Re: Application Portability?
from your story, it seems that your apps has client and application server separated by XMLRPC, which requires network connection all the time. Then based on this assumption, IMHO, the simplest way to port to PDA would be via web browser, which available natively on every PDA, and thus very easy to deploy. Otherwise, currently to run client application on windows mobile/CE for real-world commercial deployment, I couldn't find the best way other than to build it via whatever language/SDK that's native in that platform. Which almost always in C/C++. For python on PDA, I have only the chance to try on Linux Familiar on Windows PPC 2003. Which require flashing the OS inside and have to cope with long start-up time. It also lacks the libraries available on normal platform (for me, wxPython) forcing me to use GTK, and the performance wasn't really snappy which is understandable since the cpu is also slower. But for simple apps, might be fast enough. [EMAIL PROTECTED] wrote: > I have a CRM application that I've written in Ruby that currently runs > on Win32 clients as well as Linux ARM clients (Sharp Zaurus PDA's). The > application uses Qt for its GUI presentation and XMLRPC calls to > push/pull contact data back and forth. It suits my purposes, but I am > looking to port it to other platforms, such as Windows Mobile and Palm > OS PDA's. > > Getting Ruby compiled for the Palm OS is out of the question, and > getting Ruby to compile for Windows Mobile has hit many roadblocks. I > have tried looking at some Smalltalk implementations to accomplish > this, as I am willing to recode my app in another OO language if I can > definitely port it over to Windows Mobile and Palm OS. But even the > Smalltalk scenario would force me to recode the Smalltalk source itself > since one implementation wouldn't port between both platforms. > > How about Python? Could I code the application once in Python and then > port it to both PDA platforms easily? Or is this a pipe dream? I don't > know much about Python yet, but would start picking it up if it could > fit the bill... > -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about re.sub and callables
"Guyon Morée wrote:
> I can provide re.sub with a callable, but this will only be called
> with a match object, it's not possible to give it any of the other
> params.
>
> The solution I came up with to tackle this is with some funny globals,
> which doesnt feel 'right':
>
> --
> import re
>
> def test(data,pre,post):
> p = re.compile("([0-9])")
> global _pre, _post
> _pre = pre
> _post = post
>
> def repl(m):
> global _pre, _post
> return _pre + m.group(1) + _post
>
> print p.sub(repl, data)
contemporary python (nested scopes):
def test(data,pre,post):
p = re.compile("([0-9])")
def repl(m):
return pre + m.group(1) + post
print p.sub(repl, data)
old python (object binding):
def test(data,pre,post):
p = re.compile("([0-9])")
def repl(m, pre=pre, post=post):
return pre + m.group(1) + post
print p.sub(repl, data)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Application Portability?
[EMAIL PROTECTED] wrote: >I have a CRM application that I've written in Ruby that currently runs >on Win32 clients as well as Linux ARM clients (Sharp Zaurus PDA's). The >application uses Qt for its GUI presentation and XMLRPC calls to >push/pull contact data back and forth. It suits my purposes, but I am >looking to port it to other platforms, such as Windows Mobile and Palm >OS PDA's. > >Getting Ruby compiled for the Palm OS is out of the question, and >getting Ruby to compile for Windows Mobile has hit many roadblocks. I >have tried looking at some Smalltalk implementations to accomplish >this, as I am willing to recode my app in another OO language if I can >definitely port it over to Windows Mobile and Palm OS. But even the >Smalltalk scenario would force me to recode the Smalltalk source itself >since one implementation wouldn't port between both platforms. > >How about Python? Could I code the application once in Python and then >port it to both PDA platforms easily? Or is this a pipe dream? I don't >know much about Python yet, but would start picking it up if it could >fit the bill... > > > Hello, I know that this isn't a fashionable thing to write on a dynamic language newsgroup but I would really recommend switching to Java for your work if you are looking at recoding it. I'm running Java on handhelds and it works well. If you want to use dynamic languages then you can use Jytjon, there is an unofficial port of Jython for Personal Profile - I'm not sure how robust it is but you could take a look at that. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
Jay wrote: > ok have this program and i set a socket 2 connect to the server...so i > can chat on the channels and stuff. my question is how would i go about > set a socket directly 2 an individual query? Don't take this the hard way, but this question doesn't make sense, and your source code does neither. It's riddled with inconsistencies and errors, and I can only barely grasp the fundamental concept behind it... Anyway, before taking on a project of this size I'd recommend you to do something smaller in Python and get yourself aquainted with the language (and maybe programming in general). Python is a language with a shallow learning curve, but still you must master several things such as classes/instances/everything is an object/docstrings are string before being able to programm successfully. Why not start with the tutorial at www.python.org and work your way up from there? --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb Python API: Unable to connect
Hi, First thanks to all of you for helping. It seems there was some error in my instance configuration or something. As a last resort I unistalled MySQL and then reinstalled in another drive. And bingo everything is working fine. I am able to connect through Python API, too. I copied the old data directory to the new data folder. So my data is also intact. Posted just to inform all *Cheers* Regards Mondal -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Shane Hathaway <[EMAIL PROTECTED]> writes: > Andrew Durdin wrote: >> On 12/28/05, Shane Hathaway <[EMAIL PROTECTED]> wrote: >> >>>I just found a 125 character solution. It's actually faster and more >>>readable than the 133 character solution (though it's still obscure.) >> Having spent a good deal of time and effort, and not getting below >> 144 >> characters, I am now very eager to see how these shorter versions >> work, particularly the 6 120-character solutions. I also expect that >> someone (I'll certainly give it a try) will produce a yet shorter >> version after the contest closes, based on the knowledge from the >> winning solutions. > > Roberto Alsina fully documented his 120 byte solution here: > > http://www.pycs.net/lateral/weblog/2005/12/29.html#P333 > > My 120 byte solution is equivalent. Many others probably did the same > thing. Python's philosophy of one way to do it seems to be leading us > all down the same road. Here's a different way: it generates the output column-wise, then uses zip to assemble line-wise. The additional loop around zip's result probably kills it, for easier redability it's 163 bytes, but a few bytes could easily be spared. Thomas X=' _ _ _ | _| _ |_|_' Y=0x23018F406A3530EC273F008 j="".join seven_seg=lambda n:j(j(c)+"\n"for c in zip(*[X[Y>>m+int(d)*9&7::8]for d in n for m in(6,3,0)])) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4.2 gcc 3.4.4 Solaris 8 build issues
Holger Joukl wrote: > Now, I am still not 100 % sure about what I need to do. I need > C++-extensions, but I do not want to link anything statically with > Python, i.e. everything will be dynamically imported extension > modules. I *think* I can build Python C-only, avoiding possible > runtime problems with C++-extensions that might have been built with > different C++ compilers. > > Can anyony clear that up? On Solaris 8, yes you don't need to link Python with a C++ compiler. This is thanks the ELF's .init section. > 2. We have some stuff in non-standard locations here. To build > properly, I need to tell this to configure (using CXX, CPPFLAGS, > LD_LIBRARY_PATH). Unfortunately, none of this > gets communicated to > the setup.py step with its find_library_file() stuff, so it is also > necessary to either modify setup.py or add a setup.cfg file. Why do you say that? If you set CC before invoking configure, it will get into Makefile, and from there into setup.py. More generally: setup.py will take everything from Makefile, so just check whether Makefile looks right. As for LD_LIBRARY_PATH: If it is set when setup.py is running, it will certainly apply. However, I really recommend to use crle(8) instead: crle -u -l /opt/sfw/lib Then, your users will never have to set LD_LIBRARY_PATH for /opt/sfw/lib. Alternatively, set LD_RUN_PATH or pass -Wl,-R/opt/sfw/lib to the linking compiler: this will encode the path into the binary, so you still don't need to set LD_LIBRARY_PATH at runtime. > ?? Is this a known problem on Solaris? It's known to me :-) I had not time to investigate it further. > Der Inhalt dieser E-Mail ist vertraulich. So ein Quatsch. Selbst Google hat jetzt eine Kopie dieser Mail: http://tinyurl.com/8qghw Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
Jay wrote:
> ok have this program and i set a socket 2 connect to the server...so i
> can chat on the channels and stuff. my question is how would i go about
> set a socket directly 2 an individual query?
The last part of this paragraph is completely incomprehensible.
> my program is right here...
> http://h1.ripway.com/jay001/CopyofPyIRCnMo.txt
Ah, thank you. Now I can see what you're trying to accomplish:
>if sys.platform == 'linux':
>print "Cant run on a gay linux box!"
>print "Get windows! XP or new... Vista!"
>sys.exit
Not only is this obnoxious, it doesn't even work.
>def dccpopuper(self):
>"""Kill everyone with 30 pop ups requesting a dcc chat"""
>try:
>for number in range(31):
>self.irc.send("DCC CHAT" + self.CHANNEL+"\r\n")
>irc.generateNICK()
>time.sleep(5)
>print number*10
>except:
>print "I know u want 2 kill them but connect first"
Not only is this _extremely_ obnoxious, but it doesn't even work. Don't
expect any help from me.
-- David
--
http://mail.python.org/mailman/listinfo/python-list
[Newbie] Plone/workflow change ownership
Hi all, I would like to change the ownership of an object when changing its state. However when I call : obj=state_change print obj.getOwnerTuple() I get (['MyPortal', 'portal_workflow', 'TC_Workflow'], 'scripts') with scripts as owner. The method changeOwnership do nothing. Are there any tips to change the ownership during a state change? Thanks in advance and have a pretty new year. -- Frédéric Willem -- http://mail.python.org/mailman/listinfo/python-list
pyvm source code
Hi. pyvm is a program that can run python 2.4 bytecode. It can also run the bytecode of the 'pyc compiler' and consequently it can run python source code. It's written from the scratch and it has only been tested on a x86/Linux system. It's not portable yet, neither ready for the simple user, not to mention that gcc >= 3.4 is required to compile it :) What's good about it is that it's small and easier to hack and write large scale programs using pyvm as the base runtime. On the other hand, pyvm is not compatible with python and AFAIC there is no plan doing this as a hobby. The source code is available under LGPL at: http://students.ceid.upatras.gr/~sxanth/pyvm/ Enjoy, Stelios -- http://mail.python.org/mailman/listinfo/python-list
Re: new-style classes multiplication error message isn't veryinformative
Steven D'Aprano REMOVETHIScyber.com.au> writes: > > On Fri, 30 Dec 2005 03:47:30 +, Jon Guyer wrote: > > > We have a rather complicated class that, under certain circumstances, knows > > that it cannot perform various arithmetic operations, and so returns > > NotImplemented. As a trivial example: > > Why don't you raise the exception yourself? > > (Note the difference between NotImplemented and NotImplementedError.) Because although A may not know how to multiply B, B might know how to multiply A > I'd never noticed the behaviour of Python where it takes a return value of > NotImplemented and raises a ValueError. Unless somebody can tell me why > this is justified, I consider this at best a wart. If I return something, > that's my return value! I don't see why arithmetic operations are special > enough to justify this special behaviour. Python Reference Manual, Section 3.2: NotImplemented This type has a single value. There is a single object with this value. This object is accessed through the built-in name NotImplemented. Numeric methods and rich comparison methods may return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) Its truth value is true. This is exactly the behavior we want. Our code paths are simpler and less error prone if A and B don't both know how to multiply with each other, and this seems to be exactly what NotImplemented and __mul__/__rmul__ are designed for. -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphviz/dot language formatter
Hi, the recently added boost.graph python binding could be most useful: http://www.osl.iu.edu/~dgregor/bgl-python/#download -- http://mail.python.org/mailman/listinfo/python-list
Re: pyvm source code
stelios xanthakis si è profuso/a a scrivere su comp.lang.python tutte queste elucubrazioni: > What's good about it is that it's small and easier to > hack and write large scale programs using pyvm as the > base runtime. On the other hand, pyvm is not compatible > with python and AFAIC there is no plan doing this as > a hobby. I'm sorry I don't get it. Could you please explain it better? What are the advantages of this pyvm compared to the 'original' Python? Python is available on x86-linux, so it's not an additional platform. Maybe it's faster? Has it got a smaller memory footprint? Or what? -- Alan Franzoni <[EMAIL PROTECTED]> - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E -- http://mail.python.org/mailman/listinfo/python-list
csrss.exe & Numeric
I have a function that uses the Numeric module. When I launch the function csrss.exe consumes 60 / 70 % cpu power rather than having python / Numeric run at full speed. Has anyone encountered this problem before? It seriously messes up my Numeric performance. I'm running 2.4.2 on xp. Cheers, Jelle -- http://mail.python.org/mailman/listinfo/python-list
Re: pyvm source code
EleSSaR^ wrote: >>What's good about it is that it's small and easier to >>hack and write large scale programs using pyvm as the >>base runtime. > > I'm sorry I don't get it. Could you please explain it better? What are the > advantages of this pyvm compared to the 'original' Python? I think he said it: it's small(er) and easier to hack. He also says it is easier to write large-scale programs with it than with CPython, but I find that hard to believe. Whether "small and easy to hack" has any value to you depends on whether you ever wanted to hack a virtual machine. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Application Portability?
Neil Benn wrote: > Hello, > > I know that this isn't a fashionable thing to write on a > dynamic language newsgroup but I would really recommend switching to > Java for your work if you are looking at recoding it. I'm running Java > on handhelds and it works well. If you want to use dynamic languages > then you can use Jytjon, there is an unofficial port of Jython for > Personal Profile - I'm not sure how robust it is but you could take a > look at that. > > > Cheers, > > > Neil I was thinking this to myself as well, as Java should be available for most of these platforms. It's just that I don't really want to use Java unless I'm absolutely forced to :-) Can't help it coming from scripting languages like Perl and Ruby, plus toying around in Smalltalk. I'm sure that Python would be useful to pick up too, if I have the time and effort. It seems as if the libraries available for Python are considerable compared to other languages. Everyone's responses are appreciated for sure in this thread. The web browser idea is a good one too, as my GUI isn't that sophisticated, and I could get away implementing it as a basic one-page-at-a-time web app. Just have to research how to pull off all of the XMLRPC calls from within the web page coding. Should be interesting how I can pull all of this off! -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Thomas Heller wrote: > X=' _ _ _ | _| _ |_|_' > Y=0x23018F406A3530EC273F008 > j="".join > seven_seg=lambda n:j(j(c)+"\n"for c in zip(*[X[Y>>m+int(d)*9&7::8]for d in n > for m in(6,3,0)])) Interesting bit: Although there are more 3-char combinations when you read vertically, they compact better. If A=" ", B="_" and C="|", this 12 char string contains al possible combinations: BBBABAAACACC which is 2 chars shorter than the best for horizontal combinations: ABAAACBABCBCAC Still, I don't think this vertical idea can go below 123 or 124, but it's good :-) Now I wonder what the 119 solution is! -- http://mail.python.org/mailman/listinfo/python-list
Re: new-style classes multiplication error message isn't very informative
Jon Guyer wrote: > >>> This is a fake line to confuse the stupid top-posting filter at gmane > > We have a rather complicated class that, under certain circumstances, knows > that it cannot perform various arithmetic operations, and so returns > NotImplemented. As a trivial example: > > >>> class my: > ... def __mul__(self, other): > ... return NotImplemented > ... > >>> my() * my() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for *: 'instance' and 'instance' > > This error message isn't hugely meaningful to many of our users (and in > complicated expressions, I'd certainly benefit from knowing exactly which > subclasses of 'my' are involved), but it beats the behavior with new-style > classes: > > >>> class my(object): > ... def __mul__(self, other): > ... return NotImplemented > ... > >>> my() * my() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: can't multiply sequence to non-int > > After a lot of googling and a lot of pouring over abstract.c, I now > understand that object() is defined with a tp_as_sequence, and so the error > message is the result of the last-ditch effort to do sequence concatentation. > > What if I don't want to permit sequence concatenation? > Is there a way to unset tp_as_sequence? > Should I be inheriting from a different class? We started inheriting from > object because we want a __new__ method. > > The "'instance' and 'instance'" message would be OK, but even better is the > result of this completely degenerate class: > > >>> class my(object): > ... pass > ... > >>> class your(my): > ... pass > ... > >>> my() * your() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for *: 'my' and 'your' > > That's an error message I can actually do something with. Is there any way > to get this behavior when I do have a __mul__ method and sometimes return > NotImplemented? > > We're doing most of our development in Python 2.3, if it matters. This is a bug in Python. See this thread: http://mail.python.org/pipermail/python-dev/2005-December/059046.html and this patch: http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=1390657 for more details. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing cgi parameters to script...
Diez B. Roggisch wrote: > sophie_newbie wrote: > >>Is there any way that I can pass cgi parameters to my script locally, >>before i upload it to the webserver, so that i can debug it. > > You might think of using CGIHttpServer to test your scripts in a > server-environment - while still being local. Which can be as simple as typing python -c "import CGIHTTPServer; CGIHTTPServer.test()" from the command line in the root dir of your site (the dir that contains the cgi-bin dir). Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: new-style classes multiplication error message isn't very informative
gmail.com> writes: > This is a bug in Python. See this thread: > http://mail.python.org/pipermail/python-dev/2005-December/059046.html OK, thanks. This doesn't strike me as the same issue (but maybe it is). We're not getting NotImplemented returned, we're getting a TypeError; just not a good TypeError. > and this patch: > http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=1390657 > > for more details. The patch certainly appears to be on topic, though. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: help with lists and writing to file in correct order
[EMAIL PROTECTED] wrote:
> hey mike-the sample code was very useful. have 2 questions
>
> when i use what you wrote which is listed below i get told
> unboundlocalerror: local variable 'product' referenced before
> assignment.
You would get this error if you have a that doesn't have an . Do you have some that are not products? If so you
need to filter them out somehow. Or have you misspelled something? Your
sample data has id="foodName" not "dealName".
You might do better with an incremental development. Start with
for row in bs('tr'):
print row
and expand from there. At each step use print statements to make sure
you are finding the data you expect.
Kent
if i however chnage row to incident in "for incident in
> bs('tr'):" i then get mytuples printed out nicely but once again get a
> long list of
>
> [('pizza;','pizza hut;', '3.94;')]
> [('pizza;','pizza hut;', '3.94;')]
>
>
> for row in bs('tr'):
> data=[]
> for incident in row('h2', {'id' : 'dealName'}):
> productlist = []
> for oText in incident.fetchText( oRE):
> productlist.append(oText.strip() + ';')
> product = ''.join(productlist)
>
> for incident in row('a', {'name' : 'D0L3'}):
> storelist = []
> for oText in incident.fetchText( oRE):
> storelist.append(oText.strip() + ';')
> store = ''.join(storelist)
>
> tuple = (product, store, price)
> data.append(tuple)
> print data
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: reading files into dicts
On 30/12/05, Chris F.A. Johnson <[EMAIL PROTECTED]> wrote: On 2005-12-30, Tim Williams (gmail) wrote:> Apologies for the top post, it was my first attempt at using gmail's> pda-enabled web interface. There is no option to bottom post.Can you not move the cursor? Nope, there is a checkbox option to include the original post, if you include it, it appears under your new text. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Application Portability?
[EMAIL PROTECTED] wrote: > Neil Benn wrote: >> I know that this isn't a fashionable thing to write on a >>dynamic language newsgroup but I would really recommend switching to >>Java for your work if you are looking at recoding it. > > I was thinking this to myself as well, as Java should be available for > most of these platforms. It's just that I don't really want to use Java > unless I'm absolutely forced to :-) Can't help it coming from scripting > languages like Perl and Ruby, plus toying around in Smalltalk. Another option I've suggested in the past is to use Lua instead. It's certainly much closer to Perl/Ruby/Smalltalk/Python than any of them are to Java, and while I don't know whether it is supported on the specific platforms you want, it is widely supported including on the Palm. It also has the Palm OS support that all current versions of Python on the Palm are sorely lacking. (Look for Plua, most likely the most recent Plua2 beta...) -Peter -- http://mail.python.org/mailman/listinfo/python-list
WMI - invalid syntax error?
Hi,
I am running python 2.4.2 on win xp pro. I have the WMI module from
Tim Golden (http://tgolden.sc.sabren.com/python/wmi.html).
I have some code which does this...
MyScript.py
--
import wmi
# the ip of my own local desktop
machine = "1.2.3.4"
try:
w = wmi.WMI(machine) # also tried, wmi.WMI(computer=machine)
except Exception, e:
print "ERROR:", e
c:>python
>> from MyScript import *
>>> ERROR: -0x7ffbfe1c - Invalid syntax
>> import wmi
>> w = wmi.WMI("1.2.3.4")
>>
So when I import the script I get the "invalid syntax" error (which
comes from the line, w = wmi.WMI())
but in the same window if I just type it in manually I get no error.
Any ideas???
--
http://mail.python.org/mailman/listinfo/python-list
python code optimization
Hi,I know that sometimes optimization is not good idea.So I want to know what you think about this one:we have code like this: tables = []for i in ... : tables.extend(...)we optimize code like this:tables = []pfTablesExtend = tables.extendfor i in ... : pfTablesExtend(...)I what to know is this bad idea? Say you opinion about that!-- Best RegardsDarius Kučinskas -- http://mail.python.org/mailman/listinfo/python-list
Re: WMI - invalid syntax error?
here's the trace... File "MyScript.py", line 10, wmiObj = wmi.WMI(machine) File "wmi.py", line 519, in __init__ handle_com_error (error_info) File "wmi.py", line 131, in handle_com_error raise x_wmi, "\n".join (exception_string) x_wmi: -0x7ffbfe1c - Invalid syntax -- http://mail.python.org/mailman/listinfo/python-list
Re: WMI - invalid syntax error?
one more note, I am using WMI v0.6 however, I also tried it with the latest version 1.0 rc2. -- http://mail.python.org/mailman/listinfo/python-list
RE: WMI - invalid syntax error?
[py]
> import wmi
> # the ip of my own local desktop
> machine = "1.2.3.4"
> try:
> w = wmi.WMI(machine) # also tried, wmi.WMI(computer=machine)
> except Exception, e:
> print "ERROR:", e
.
.
> c:>python
> >>> from MyScript import *
> >>> ERROR: -0x7ffbfe1c - Invalid syntax
.
.
> here's the trace...
>
> File "MyScript.py", line 10,
>wmiObj = wmi.WMI(machine)
> File "wmi.py", line 519, in __init__
>handle_com_error (error_info)
> File "wmi.py", line 131, in handle_com_error
>raise x_wmi, "\n".join (exception_string)
> x_wmi: -0x7ffbfe1c - Invalid syntax
.
.
> one more note, I am using WMI v0.6 however, I also tried it with
> the latest version 1.0 rc2.
OK, so if I understand you: at the interpreter you can do this:
import wmi
w = wmi.WMI ("1.2.3.4")
# no problem
but if you put it into a file and then import * from
that file, it fails with a wmi exception:
import wmi
w = wmi.WMI ("1.2.3.4")
from blah import *
## some kind of x_wmi exception happens here
And this happens on wmi 0.6 and 1.0rc2.
Is this correct?
It's just that you've got several things which could
to be blurring the issue - the fact that you're using
an explicit IP address rather than passing no params,
which will then use the local machine automatically;
you've added an exception handler which doesn't do much;
your traceback in the second email doesn't (quite) match
the MyScript in the first. It's not that these are wrong -
I'm just trying to eliminate non-essentials to get to the
core of the thing.
In short, what I wrote above works for me on 0.6 and 1.0rc2.
A syntax error usually means that the moniker's got problems -
that's the string which the wmi module builds up on your
behalf to get something to pass to MS COM.
Could you just post (or send by private email if you prefer)
the exact script you're running? If you want to send it
privately, please us mail timgolden.me.uk.
Thanks
TJG
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
--
http://mail.python.org/mailman/listinfo/python-list
MidiToText : EventDispatcher instance has no attribute 'sysex_events'
Trying to convert midi to text using MidiToText.py. I get the following: midi_port: 0 Traceback (most recent call last): File "MidiToText.py", line 176, in ? midiIn.read() File "C:\Python24\Lib\site-packages\midi\MidiInFile.py", line 24, in read p.parseMTrkChunks() File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 167, in parseMTrkChunks self.parseMTrkChunk() # this is where it's at! File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 129, in parseMTrkChunk dispatch.sysex_events(sysex_data) AttributeError: EventDispatcher instance has no attribute 'sysex_events' any ideas? thank you, Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: Python as a Server vs Running Under Apache
Matt Helm wrote: > > I am starting the design phase of a large project (ERP) where the > backend will mostly be Python (or Ruby) providing web services. > > In this type of usage, is there any benenfit to running under Apache > as opposed to a pure Python solution using Medusa, TwistedMatrix, or > the like? > > Thanks, > Matt > > If it is a large project and you like Python as back end be sure to evaluate using Zope (which can use Apache as a front end for serving up static info and for SSL, etc.). With Zope you get a lot of "free" stuff like XMPRPC, DAV, FTP, that can take quite a lot of time to implement from scratch. It may not be for you, but you owe it to yourself to take a look. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: WMI - invalid syntax error?
Tim Golden wrote: > Could you just post (or send by private email if you prefer) > the exact script you're running? If you want to send it > privately, please us mail timgolden.me.uk. I am truly unsure what the problem could be, and the fact that the error says "invalid syntax" ...just doesn't make much sense to me. Perhaps I could print out the moniker and see if that looks right...any suggestion on how to do that? Anyway I have this: import wmi def ppn(machine=None): try: wmiObj = wmi.WMI(machine) print "Got it:", wmiObj except Exception, e: print "Error:", e This is the same code, line for line, as i am using in a bigger script. It's got to be something stupid...just doesn't make any sense. Wish the error was more specific. -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E04 - Leadership! Google, Guido van Rossum, PSF
Martin P. Hellwig wrote: [...] - (complex elaborations) > So the sum it up my unanswered question to you so far are: > - What is your definition of "Efficiency" http://lazaridis.com/efficiency/definitions.html (as stated on the website, any feedback is welcome. But please not within this thread). > - What is your definition of "Management" I have none (I use internally the hellenic word, which explains/defines itself) > - What is you definition of "Communication" (to compare it with mine above) I have none (there was no need for me to define, and at this point its not a priority). > - What are your reasons that I should accept you as authoritative on the > subject of "Efficiency Management"? a) The process itself you can verify it on my website. b) Rate the public application/verification of the process this is difficult, as the major evaluations (NetBeans, Eclipse) are huge and complex to follow (google archives) d) Reference Customers (they are not available yet) c) Initiate a Free Website Review (the simplest way): http://lazaridis.com/services/index.html and rate the results > - What has all that to do with Python except for that Guido is related > to Google and Python? Python is still on my list of possible languages for a long-term project. Thus I am still evaluating it. This thread here is part of a python evaluation: http://lazaridis.com/core/eval/index.html . -- http://lazaridis.com -- http://mail.python.org/mailman/listinfo/python-list
RE: WMI - invalid syntax error?
[py]
| Tim Golden wrote:
| > Could you just post (or send by private email if you prefer)
| > the exact script you're running? If you want to send it
| > privately, please us mail timgolden.me.uk.
|
| I am truly unsure what the problem could be, and the fact that the
| error says "invalid syntax" ...just doesn't make much sense to me.
| Perhaps I could print out the moniker and see if that looks
| right...any
| suggestion on how to do that?
|
| Anyway I have this:
[.. snipped code ..]
OK, well just to confirm, I saved your code
as blah3.py, started an interpreter
(Python 2.4.2 on XP Pro) and did:
from blah3 import *
blah3.ppn ()
and all was well.
Which obviously doesn't help you at all.
Get version 0.6b for the moment (if you don't have
it - http://tgolden.sc.sabren.com/python/downloads/wmi-0.6b.py).
Then set the _DEBUG flag to True. (v0.6 doesn't have this flag).
import wmi
wmi._DEBUG = True
c = wmi.WMI ()
# This will print a moniker looking something like this:
#
winmgmts:{impersonationLevel=Impersonate,authenticationLevel=Default}/ro
ot/cimv2
and let me know what comes out.
TJG
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
--
http://mail.python.org/mailman/listinfo/python-list
Re: WMI - invalid syntax error?
Tim Golden wrote:
>
> import wmi
> wmi._DEBUG = True
>
> c = wmi.WMI ()
> # This will print a moniker looking something like this:
> #
> winmgmts:{impersonationLevel=Impersonate,authenticationLevel=Default}/ro
> ot/cimv2
>
>
> and let me know what comes out.
I ran it twice, first it worked, second time it didnt...
winmgmts:{impersonationLevel=Impersonate,authenticationLevel=Default}/root/cimv2
winmgmts:{impersonationLevel=Impersonate,authenticationLevel=Default}/root/cimv2
..but same moniker. Something must be happening somewhere causing it
to get fouled up. I'm gonna try on a different PC.
--
http://mail.python.org/mailman/listinfo/python-list
Re: query on python list
I'm having trouble determining what you want but I think there are a couple of problems in your code: list2 = ['1','2','5',4] did you mean list2 = ['1','2','3','4'] Note missing quotes around the 4 and 5 instead of 3 If you want to know if list2 is found in list 1 it is as simple as: if list2 in list1: # # Do something here # if you want to know if any member of list2 is found in any list in list 1 then you can just do: Found=max([y in x for y in list2 for x in list1]) works and you should have some fun picking this one-liner apart . -Larry Bates Mike Meyer wrote: > [EMAIL PROTECTED] writes: > >>hi tim >>thanks for the help >>acutally i dint tell u the whole problem >>i have list of lists, for ex >> >>list1 =[ ['a','b','c','d','e'] , ['1','2','3','4'] , ['A','B','C','D'] >>] >> >>and another list >> >>list2 = ['1','2','5',4] >> >>now am searching the items of list2 in list1 as below >> >>Found = True >>for i in list1: >>for j in i: >>if not list2[1] == j or not list2[2] == j: >>if not list2[0] == j: >>Found = False >>elif list2[0] == j: >>Found = True >>break >> >>now though it finds the the key in between and sets the "Found=True", >>but later in the next list of if one item doesnt match it sets again >>Found = False >> >>i hope am clear this time > > > You have half the solution. Basically, you should set Found to one > state, and then only set it againn if it changes. For instance: > > Found = True > for i in list1: > for j in i: > if not list2[1] == j or not list2[2] == j: >if not list2[0] == j: > Found = False > > This will exit the outer loop with Found being False if and only if > the nested if's in your inner loop set it to False; you never need to > set it to True. Alternatively, set the initial state to False, and > only set it to True if you find something. > > For efficiency, you can break from the inner loop, and then check > found after the inner loop and break a second time if it's changed. > > BTW, the nested ifs in your inner loop don't do what your description > says they should. > > > > Mike Meyer <[EMAIL PROTECTED]> > http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: oop in python
novice wrote:
> hello over there!
> I have the following question:
> Suppose I created a class: class Point:
> pass
> then instanciated an instance: new = Point()
> So now how to get the instance new as a string: like ' new ' ; Is
> there any built in function or method
> for eg:
>
> class Point:
>def _func_that_we_want_(self):
> return ...
> new._func_that_we_want_() ---> ' new '
>
Just a wild guess, but I think he wants to refer to it by a
name. The best way to do this is to put the class instance
in a dictionary and make the key 'new'
instancedict={}
instancedict['new']=Point()
then you can call methods by:
instancedict['new'].somemethod()
-Larry Bates
--
http://mail.python.org/mailman/listinfo/python-list
Re: python code optimization
Darius Kučinskas wrote: > I know that sometimes optimization is not good idea. It's neither good nor bad. Whether or not to optimize is merely a decision that should not be made without considering the cost, and without a real need driving it. The need can only be seen by profiling your code and measuring inadequate performance (which implies a standard by which you're judging it). The cost is not only the time it takes to optimize (which is often small) but more importantly the effect on the readability and maintainability of the code. Most people don't bother measuring, and most ignore the readability cost, and that's why most optimization is "premature" and why "sometimes optimization is not a good idea" (if you really want to express it that way). > So I want to know what you think about this one: ... > we optimize code like this: > tables = [] > pfTablesExtend = tables.extend > for i in ... : > pfTablesExtend(...) > > I what to know is this bad idea? Say you opinion about that! It's very easy to judge based on the guidance I gave above. Was the unoptimized code really too slow? And does the result actually improve the speed sufficiently? That is, did you measure before and after and is the reduction in runtime significant? If the answer to any of these questions is "no", then optimizing was a bad idea. And does the value of the optimization outweigh the cost? In this case, as a casual reader of that code (perhaps missing some context?), I would say that reading "pfTablesExtend" surprises me, since I can't tell what "pf" means, and there are no comments pointing out that the performance without that extra stuff was insufficient. If I were maintaining your code, I would probably hesitate a moment out of uncertainty about why anyone would have done that in the first place, and then I'd simply remove the optimization, assuming the programmer had prematurely optimized. You can judge for yourself whether that makes the time involved in optimizing this worth it. ;-) -- Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: MidiToText : EventDispatcher instance has no attribute 'sysex_events'
On Fri, 2005-12-30 at 09:52, tim wrote: > Trying to convert midi to text using MidiToText.py. > I get the following: > > midi_port: 0 > Traceback (most recent call last): > File "MidiToText.py", line 176, in ? > midiIn.read() > File "C:\Python24\Lib\site-packages\midi\MidiInFile.py", line 24, in read > p.parseMTrkChunks() > File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 167, > in parseMTrkChunks > self.parseMTrkChunk() # this is where it's at! > File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 129, > in parseMTrkChunk > dispatch.sysex_events(sysex_data) > AttributeError: EventDispatcher instance has no attribute 'sysex_events' Try changing "def sysex_event(self, data):" in ...\midi\EventDispatcher.py to "def sysex_events(self, data):" Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: WMI - invalid syntax error?
py wrote: >Something must be happening somewhere causing it > to get fouled up. I'm gonna try on a different PC. I tried on another PC, same problem. Also, I added "reload(wmi)" before I create an instance of wmi.WMI just to see what happens, so I hve... import wmi def ppn(machine=None): try: reload(wmi) wmiObj = wmi.WMI(machine) except Exception, e: print "Error: " + str(e) ...now I get this as the error message.. Error: (-2147221020, 'Invalid syntax', None, None) Slightly different than before...but same message. -- http://mail.python.org/mailman/listinfo/python-list
Re: new-style classes multiplication error message isn't veryinformative
On Fri, 30 Dec 2005 13:23:30 +, Jon Guyer wrote: > Steven D'Aprano REMOVETHIScyber.com.au> writes: > >> >> On Fri, 30 Dec 2005 03:47:30 +, Jon Guyer wrote: >> >> > We have a rather complicated class that, under certain circumstances, knows >> > that it cannot perform various arithmetic operations, and so returns >> > NotImplemented. As a trivial example: >> >> Why don't you raise the exception yourself? >> >> (Note the difference between NotImplemented and NotImplementedError.) > > Because although A may not know how to multiply B, B might know how to > multiply A Given the way Python is now, that's fair enough. But see below: >> I'd never noticed the behaviour of Python where it takes a return value >> of NotImplemented and raises a ValueError. Unless somebody can tell me >> why this is justified, I consider this at best a wart. If I return >> something, that's my return value! I don't see why arithmetic >> operations are special enough to justify this special behaviour. > > Python Reference Manual, Section 3.2: > > > > NotImplemented This type has a single value. There is a single object > with this value. This object is accessed through the built-in name > NotImplemented. Numeric methods and rich comparison methods may return > this value if they do not implement the operation for the operands > provided. (The interpreter will then try the reflected operation, or > some other fallback, depending on the operator.) Its truth value is > true. > > > > This is exactly the behavior we want. Our code paths are simpler and > less error prone if A and B don't both know how to multiply with each > other, and this seems to be exactly what NotImplemented and > __mul__/__rmul__ are designed for. And I argue that they *shouldn't be*. If my code returns some object, Python shouldn't muck about with it. Making a special case behaviour for arithmetic is poor design -- arithmetic isn't special enough to justify the special behaviour. If you need to trigger a special behaviour (such as "I don't know how to do this multiplication, please try the other object") the correct way to do it is with an exception, just as iterators use the StopIteration exception to trigger special behaviour, or list iteration use IndexError. Returning a magic value that is captured and handled specially is just wrong. Exceptions are more generous too: Python could use your exception's message string when printing the traceback, instead of making its own. All of the above is, of course, in my not-so-humble opinion, and none of it solves your problem. Sorry. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Shane Hathaway wrote:
> Andrew Durdin wrote:
>
>>On 12/28/05, Shane Hathaway <[EMAIL PROTECTED]> wrote:
>>
>>
>>>I just found a 125 character solution. It's actually faster and more
>>>readable than the 133 character solution (though it's still obscure.)
>>
>>
>>Having spent a good deal of time and effort, and not getting below 144
>>characters, I am now very eager to see how these shorter versions
>>work, particularly the 6 120-character solutions. I also expect that
>>someone (I'll certainly give it a try) will produce a yet shorter
>>version after the contest closes, based on the knowledge from the
>>winning solutions.
>
>
> Roberto Alsina fully documented his 120 byte solution here:
>
> http://www.pycs.net/lateral/weblog/2005/12/29.html#P333
>
> My 120 byte solution is equivalent. Many others probably did the same
> thing. Python's philosophy of one way to do it seems to be leading us
> all down the same road.
>
> However, it still feels like there's room for improvement. I have a 123
> byte solution based on a fairly repetitive 21 character string; if I
> could compress the representation of the string, it could win.
Apparently there was as someone put out a 119 byte solution. I can't get
to Roberto's code at present (perhaps he's suffering a bandwidth
crisis?), but it seems that my 120 character solution is different. It
sounds like he encoded his as a row at a time and did two loops one for
each character and one for each row. I encoded the data per character
and did three loops one per column, one per character and one per row.
I'm sure that's not clear, so here's the code:
g=''.join;seven_seg=lambda i:g(
g(' _|x|'[ord("~$]m'k{d\x7fo"[int(n)])>>s&j]
for n in i for j in(2,1,4))+'\n'for s in(6,0,3))
I've replaced the unprintable characters and added some preemptive
linebreaks so that hopefully this won't get too munged. It's all clear
now, right? Two hints: 6,0,3->row, 2,1,4->column and the 6 and 1 have to
be where they are to exploit the property that the top row only ever has
a center character in it. That way things can be encoded in 7-bits and
fit in a character string that Python likes. The order of the other loop
indices is mostly accidental but not all permutations may work.
I'm off to try to figure out how to do it the other way now, before the
code gets revealed.
-tim
-tim
--
http://mail.python.org/mailman/listinfo/python-list
Xah's Edu Corner: Tech Geekers and their Style
Sometimes you want your text to flow into multiple columns, as in
newspaper's layout. However, as of 2005-12 this is not yet possible.
One can make-do by hard-coding it into HTML TABLE using multiple
columns. It is a pain because when you change your text, you have to
manually cut and paste to justify each and every columns by
trial-n-error.
A proposed solution is in CSS3 “Multi-column layout”, drafted in
2001 but not yet in any mainstream browsers as of 2005-12. See
http://www.w3.org/TR/2001/WD-css3-multicol-20010118/
With all the whizbang of styles and features in CSS2, a basic,
necessary, functional layout feature as multi-columns is not there yet.
This is a indication of the fatuousness of the IT industry's
technologies and its people.
Xah
[EMAIL PROTECTED]
∑ http://xahlee.org/
--
Xah Lee wrote:
sometimes in the last few months, apparently Microsoft made changes to
their JavaScript documentation website:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/1e9b3876-3d38-4fd8-8596-1bbfe2330aa9.asp
so that, one has to goddamn press the "expand" button to view the
documentation, for every goddamn page.
What the fuck is going on?
And, good url before the change are now broken (giving HTTP error 404).
Many of the newfangled buttons such as "Copy Code" doesn't goddamn work
in Safari, FireFox, iCab, Mac IE.
And, in any of these browsers, the code examples becomes single
congested block without any line breaks. e.g.
«Circle.prototype.pi = Math.PI; function ACirclesArea () { return
this.pi * this.r * this.r; // The formula for the area of a circle is
r2. } Circle.prototype.area = ACirclesArea; // The function
that calculates the area of a circle is now a method of the Circle
Prototype object. var a = ACircle.area(); // This is how you would
invoke the area function on a Circle object.»
There are two interpretations to this Microsoft's JavaScript doc
problem:
1. They didn't do it intentionally.
2. They did it intentionally.
If (1), then it would be a fucking incompetence of inordinate order. If
(2), they would be assholes, even though they have the right to do so.
On the other hand, in terms of documentation quality, technological
excellence, responsibility in software, Microsoft in the 21st century
is the holder of human progress when compared to the motherfucking Open
Sourcers lying thru their teeth fuckheads.
--
http://mail.python.org/mailman/listinfo/python-list
Xah's Edu Corner: Tech Geekers and their Style
Sometimes you want your text to flow into multiple columns, as in
newspaper's layout. However, as of 2005-12 this is not yet possible.
One can make-do by hard-coding it into HTML TABLE using multiple
columns. It is a pain because when you change your text, you have to
manually cut and paste to justify each and every columns by
trial-n-error.
A proposed solution is in CSS3 “Multi-column layout”, drafted in
2001 but not yet in any mainstream browsers as of 2005-12. See
http://www.w3.org/TR/2001/WD-css3-multicol-20010118/
With all the whizbang of styles and features in CSS2, a basic,
necessary, functional layout feature as multi-columns is not there yet.
This is a indication of the fatuousness of the IT industry's
technologies and its people.
Xah
[EMAIL PROTECTED]
∑ http://xahlee.org/
--
Xah Lee wrote:
sometimes in the last few months, apparently Microsoft made changes to
their JavaScript documentation website:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/1e9b3876-3d38-4fd8-8596-1bbfe2330aa9.asp
so that, one has to goddamn press the "expand" button to view the
documentation, for every goddamn page.
What the fuck is going on?
And, good url before the change are now broken (giving HTTP error 404).
Many of the newfangled buttons such as "Copy Code" doesn't goddamn work
in Safari, FireFox, iCab, Mac IE.
And, in any of these browsers, the code examples becomes single
congested block without any line breaks. e.g.
«Circle.prototype.pi = Math.PI; function ACirclesArea () { return
this.pi * this.r * this.r; // The formula for the area of a circle is
r2. } Circle.prototype.area = ACirclesArea; // The function
that calculates the area of a circle is now a method of the Circle
Prototype object. var a = ACircle.area(); // This is how you would
invoke the area function on a Circle object.»
There are two interpretations to this Microsoft's JavaScript doc
problem:
1. They didn't do it intentionally.
2. They did it intentionally.
If (1), then it would be a fucking incompetence of inordinate order. If
(2), they would be assholes, even though they have the right to do so.
On the other hand, in terms of documentation quality, technological
excellence, responsibility in software, Microsoft in the 21st century
is the holder of human progress when compared to the motherfucking Open
Sourcers lying thru their teeth fuckheads.
--
http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Tim Hochberg wrote:
> Shane Hathaway wrote:
>> Andrew Durdin wrote:
>>
>>> On 12/28/05, Shane Hathaway <[EMAIL PROTECTED]> wrote:
>>>
>>>
I just found a 125 character solution. It's actually faster and more
readable than the 133 character solution (though it's still obscure.)
>>>
>>> Having spent a good deal of time and effort, and not getting below 144
>>> characters, I am now very eager to see how these shorter versions
>>> work, particularly the 6 120-character solutions. I also expect that
>>> someone (I'll certainly give it a try) will produce a yet shorter
>>> version after the contest closes, based on the knowledge from the
>>> winning solutions.
>>
>> Roberto Alsina fully documented his 120 byte solution here:
>>
>> http://www.pycs.net/lateral/weblog/2005/12/29.html#P333
>>
>> My 120 byte solution is equivalent. Many others probably did the same
>> thing. Python's philosophy of one way to do it seems to be leading us
>> all down the same road.
>>
>> However, it still feels like there's room for improvement. I have a 123
>> byte solution based on a fairly repetitive 21 character string; if I
>> could compress the representation of the string, it could win.
>
> Apparently there was as someone put out a 119 byte solution. I can't get
> to Roberto's code at present (perhaps he's suffering a bandwidth
> crisis?), but it seems that my 120 character solution is different. It
> sounds like he encoded his as a row at a time and did two loops one for
> each character and one for each row. I encoded the data per character
> and did three loops one per column, one per character and one per row.
> I'm sure that's not clear, so here's the code:
>
> g=''.join;seven_seg=lambda i:g(
> g(' _|x|'[ord("~$]m'k{d\x7fo"[int(n)])>>s&j]
> for n in i for j in(2,1,4))+'\n'for s in(6,0,3))
>
> I've replaced the unprintable characters and added some preemptive
> linebreaks so that hopefully this won't get too munged. It's all clear
> now, right? Two hints: 6,0,3->row, 2,1,4->column and the 6 and 1 have to
> be where they are to exploit the property that the top row only ever has
> a center character in it. That way things can be encoded in 7-bits and
> fit in a character string that Python likes. The order of the other loop
> indices is mostly accidental but not all permutations may work.
>
> I'm off to try to figure out how to do it the other way now, before the
> code gets revealed.
>
>
> -tim
> -tim
>
>
Mine was practically identical, but with another permutation of the loop
variables:
seven_seg=lambda n,s="".join:s(
s(" _| |"[ord('w\x12][:koR\x7f{'[int(i)])>>r&j]
for i in n for j in(4,1,2))+"\n"for r in(6,3,0))
More evidence that 'there is one obvious way to do it' ;-)
Still curious about 119, though
Michael
--
http://mail.python.org/mailman/listinfo/python-list
python for with double test
hi all the is a way for doing a for with double test: example for i in range(0,10) and f==1: thanx everyone -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Tim Hochberg wrote:
> g=''.join;seven_seg=lambda i:g(
> g(' _|x|'[ord("~$]m'k{d\x7fo"[int(n)])>>s&j]
> for n in i for j in(2,1,4))+'\n'for s in(6,0,3))
>
> I've replaced the unprintable characters and added some preemptive
> linebreaks so that hopefully this won't get too munged. It's all clear
> now, right? Two hints: 6,0,3->row, 2,1,4->column and the 6 and 1 have to
> be where they are to exploit the property that the top row only ever has
> a center character in it. That way things can be encoded in 7-bits and
> fit in a character string that Python likes. The order of the other loop
> indices is mostly accidental but not all permutations may work.
I worked on a similar solution, but didn't have the idea of iterating
over a series of masks as you did with the 'j' variable. Good work.
> I'm off to try to figure out how to do it the other way now, before the
> code gets revealed.
We should have more contests like this. While the skills I applied for
the contest don't have much practical value, the mental exercise was great.
Shane
--
http://mail.python.org/mailman/listinfo/python-list
Pyrex on Darwin, gcc 3.3 optimization trouble
I am trying to build a Pyrex module on Mac OS X version 10.3.9 (don't know which big cat that is). It already builds fine on Mandrake Linux and Windows XP. I have one source file where gcc hangs if given an optimization setting of -O2 or -O3, but a level of -O works fine. Can anybody suggest an approach to debugging this? I'm comfortable on Linux but I can't find my way out of a paper bag on a Mac. Also, is there a Pyrex or distutils option for limiting the compiler optimization level, ideally on a per-platform basis? Thanks much Will Ware -- http://mail.python.org/mailman/listinfo/python-list
Re: python for with double test
[EMAIL PROTECTED] wrote: > hi all > the is a way for doing a for with double test: >example > for i in range(0,10) and f==1: > Not sure if you're asking a question, but is this what you are trying to do? : if f == 1: for i in range(0,10): ... If not, please explain more carefully what you want, maybe with an example showing more than "..." in the body so we'll understand better. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: python for with double test
for i in range(0,10): if f!=1: break ... i=0 while i<10 and f==1: ... i+=1 -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
my two solutions (well I wasn't so clever to encode everything in
strings instead of numbers, but at least it won't give warnings about
non ascii characters):
128:
j,seven_seg=''.join,lambda s:j(j(' |_ |'[i>>3*int(c)&b]for c in s for b
in(4,2,1))+'\n'for i in(306775170,1060861645,524130191))
122:
seven_seg=lambda s,j=''.join:j(j(' _ _|_| |_
|'[i>>3*int(c)&14:][:3]for c in s)+'\n'for i
in(8208,934111592,664455910))
--
http://mail.python.org/mailman/listinfo/python-list
Re: When Python *Eggs* better than Python *distutils*?? What's Eggs?
Paul Boddie wrote: > Could anyone enlighten me/us as to why the Smart Package Manager [1] > (written in Python, presented at EuroPython this year) isn't being more > closely investigated as part of a suitable solution? More closely investigated by whom, as a solution for what? Surely there is someone somewhere investigating it as a solution for something, so your presupposition that it isn't would seem to imply that you have some more specific person(s) and solution(s) in mind. :) If you are speaking with respect to setuptools, I would just point out that it is intended to be packaging-system neutral. While the easy_install package manager will work on most platforms supported by Python, it's intended only for tasks that cannot be accomplished using the local package management system. So, I've definitely "closely investigated" package management tools "as part of a suitable solution," and have recently added features to make eggs work better with package management tools. This consideration, however, does not extend to providing any special integration with any *particular* package management tools, especially since some systems (e.g. Windows) have little or no such support, and a common usage environment for Python web applications at least (shared hosting providers) offer no way to *use* the system package manager at all. That having been said, a few quick glances at Smart's source code show me that Smart itself could perhaps benefit from eggs, for example to handle plugins for channels and distribution types. Its hook system, for example, could be handled in a decentralized way. Also, in theory at least, it looks like Smart could be extended to recognize eggs and manage them as well, but I haven't looked deeply into any of these questions since they're not in scope for my efforts at this time. However, it would certainly appear that *someone* could investigate making Smart a bigger part of some "suitable solution" for something. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: python for with double test
Il 30 Dec 2005 09:02:30 -0800, [EMAIL PROTECTED] ha scritto: > hi all > the is a way for doing a for with double test: what's a 'double test' exactly? :-) 'for' does no test, it just iterates over a list. If you want to execute the iteration only if f is 1, do this: if f==1: for i in range(0,10): ... if you want to use only certain values in the range, when the value of f[i] (f may be a list, a dictionary, or whatever) is 1, you can use a list comprehension: for i in [x for x in range(0,10) if f[x]==1]: of course, if you want to make it shorter, you can define a function instead of the 'for' code block and use the list comprehension directly: def myfunction(x): ... [myfunction(x) for x in range(0,10) if f[x]==1] and you'll end up with a list of the return values of myfunction. -- Alan Franzoni <[EMAIL PROTECTED]> - Togli .xyz dalla mia email per contattarmi. To contact me, remove .xyz from my email address. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E -- http://mail.python.org/mailman/listinfo/python-list
Re: When Python *Eggs* better than Python *distutils*?? What's Eggs?
[EMAIL PROTECTED] wrote: > I have been using distuils for a while and was wondering when > Python Eggs (new project) is better? If you have a relatively simple setup script, don't need to upload your package to PyPI, and don't include any files other than .py files and C extensions in your distribution, you won't benefit much from switching to setuptools. If you have a lot of non-code files, setuptools will let you get rid of MANIFEST hassles and data file installation issues. A fairly complete list of setuptools features can be found here: http://cheeseshop.python.org/pypi/setuptools Most of these are just conveniences for the developer, that get rid of a lot of the repetitious code you have to put in setup.py, especially if you are doing anything that the distutils doesn't handle automatically. However, the "killer app" feature of setuptools is that it lets you distribute a project that depends on other software available via PyPI. Instead of having to bundle the other project inside yours, or tell users to manually download and install the dependencies. If you use setuptools, then you can take advantage of automatic dependency download and installation, making it easier for you as a developer to reuse existing open source Python code. This is the real reason setuptools and eggs and easy_install exist: to allow Python developers to reuse code without bundling or manual dependency management -- regardless of platform. (i.e., without them having to support rpm, deb, msi, dpkg, pkgsrc, and all the other nine jillion packaging systems out there). > So basically Python Eggs precompiles and compresses > binaries for you so you just have to load it to run > your app? Python eggs are a way of bundling additional information with a Python project, that allows its dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several formats for this, but the '.egg' zipfile format is a convenient one for *distributing* projects. Whether you keep them compressed or not when you install them is partly a matter of whether the project is able to be used in compressed form, and whether you want to be able to use certain documentation or debugging tools that don't always work with zip files. This .egg format is created by the "bdist_egg" command, which is basically similar to bdist_wininst or bdist_rpm, in that it creates a file you can then upload to PyPI or otherwise distribute. The main difference between .egg and win32.exe or .rpm is that .egg files can be put directly on sys.path and used, while the other formats cannot. -- http://mail.python.org/mailman/listinfo/python-list
Re: MidiToText : EventDispatcher instance has no attribute 'sysex_events'
Carsten Haese wrote: On Fri, 2005-12-30 at 09:52, tim wrote: Trying to convert midi to text using MidiToText.py. I get the following: midi_port: 0 Traceback (most recent call last): File "MidiToText.py", line 176, in ? midiIn.read() File "C:\Python24\Lib\site-packages\midi\MidiInFile.py", line 24, in read p.parseMTrkChunks() File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 167, in parseMTrkChunks self.parseMTrkChunk() # this is where it's at! File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 129, in parseMTrkChunk dispatch.sysex_events(sysex_data) AttributeError: EventDispatcher instance has no attribute 'sysex_events' Try changing "def sysex_event(self, data):" in ...\midi\EventDispatcher.py to "def sysex_events(self, data):" Hope this helps, Carsten. Yes thank Carsten! it works. Now I am trying to generate a string or a list from the output of MidiToText instead of printing to the console. I tried simply replacing the "print" in MidiToText by "return" everywhere, and renamed it to MidiToTextFile so that I would be able to do: for test_file in fulldir: f = open(test_file, 'rb') # do parsing from MidiInFile import MidiInFile midiIn = MidiInFile(MidiToTextFile(), f) f.close() outmidtxt.write(midiIn.read()) or something, to have the text version of several midi's written into one large textfile, but I got lost somewhere along the way how to do this? ...thanks again --- Begin Message --- Carsten Haese wrote: On Fri, 2005-12-30 at 09:52, tim wrote: Trying to convert midi to text using MidiToText.py. I get the following: midi_port: 0 Traceback (most recent call last): File "MidiToText.py", line 176, in ? midiIn.read() File "C:\Python24\Lib\site-packages\midi\MidiInFile.py", line 24, in read p.parseMTrkChunks() File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 167, in parseMTrkChunks self.parseMTrkChunk() # this is where it's at! File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 129, in parseMTrkChunk dispatch.sysex_events(sysex_data) AttributeError: EventDispatcher instance has no attribute 'sysex_events' Try changing "def sysex_event(self, data):" in ...\midi\EventDispatcher.py to "def sysex_events(self, data):" Hope this helps, Carsten. Yes thank Carsten! it works. Now I am trying to generate a string or a list from the output of MidiToText instead of printing to the console. I tried simply replacing the "print" in MidiToText by "return" everywhere, and renamed it to MidiToTextFile so that I would be able to do: for test_file in fulldir: f = open(test_file, 'rb') # do parsing from MidiInFile import MidiInFile midiIn = MidiInFile(MidiToTextFile(), f) f.close() outmidtxt.write(midiIn.read()) or something, to have the text version of several midi's written into one large textfile, but I got lost somewhere along the way how to do this? ...thanks again --- End Message --- -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Szabolcs Nagy wrote:
> my two solutions (well I wasn't so clever to encode everything in
> strings instead of numbers, but at least it won't give warnings about
> non ascii characters):
> 128:
> j,seven_seg=''.join,lambda s:j(j(' |_ |'[i>>3*int(c)&b]for c in s for b
> in(4,2,1))+'\n'for i in(306775170,1060861645,524130191))
>
> 122:
> seven_seg=lambda s,j=''.join:j(j(' _ _|_| |_
> |'[i>>3*int(c)&14:][:3]for c in s)+'\n'for i
> in(8208,934111592,664455910))
FWIW, here's my 121 character solution that's fully printable. (Line
breaks added.)
seven_seg=lambda s,j=''.join:j(j(
' _ _| |_ |_|'[ord('^-TR5bfmvr'[int(c)])/b%8*2:][:3]for c in s)+'\n'
for b in(64,8,1))
This solution uses the 7 lower bits of every encoded byte, rather than
the 7 upper bits that the 8 bit solutions use. 8 bits make it possible
to avoid multiplying by 2, but I wanted this version to use pure ASCII,
so I had to multiply by 2. The choice to divide rather than shift is
important because it allowed me to eliminate parentheses.
It's interesting that there seems to be no room for special cases. For
example, the top row has only two states and those states are not used
by the other rows. Therefore, the top row could be computed in a much
simpler way than the other two rows, and the other two rows could be
simplified by having only 5 possible states rather than 7. However, all
my attempts to exploit this property produced larger code.
Shane
--
http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Tech Geekers and their Style
On 30/12/2005 16:45, Xah Lee wrote: [Follow-ups trimmed to c.i.w.a.stylesheets] [snip] > A proposed solution is in CSS3 “Multi-column layout”, drafted in > 2001 but not yet in any mainstream browsers as of 2005-12. Quite rightly so, in my opinion. The Multi-column layout module is currently a working draft and, as I recall, a relatively vague one at that. It would be rather foolish to produce anything but a proof-of-concept implementation until its various aspects are finalised. [Aside] If I remember correctly, Mozilla implemented the W3C DOM Level 3 Events module, which introduced a keyboard event type (KeyEvent). In a later revision, this interface name was replaced with TextEvent. Later on, a similarly named interface (KeyboardEvent) was introduced, focusing specifically on low-level keyboard events. These radical changes wouldn't mean very much had Mozilla waited. The DOM Level 3 Events module has been a Working Group Note since November 2003. This probably marks the end of its development. [/Aside] [snip] Mike -- Michael Winter Prefix subject with [News] before replying by e-mail. -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Tech Geekers and their Style
"Xah Lee" <[EMAIL PROTECTED]> writes: > Sometimes you want your text to flow into multiple columns, as in > newspaper's layout. However, as of 2005-12 this is not yet possible. > One can make-do by hard-coding it into HTML TABLE using multiple > columns. It is a pain because when you change your text, you have to > manually cut and paste to justify each and every columns by > trial-n-error. > > A proposed solution is in CSS3 “Multi-column layout”, drafted in > 2001 but not yet in any mainstream browsers as of 2005-12. See > http://www.w3.org/TR/2001/WD-css3-multicol-20010118/ > > With all the whizbang of styles and features in CSS2, a basic, > necessary, functional layout feature as multi-columns is not there yet. > This is a indication of the fatuousness of the IT industry's > technologies and its people. In general, the IT industry doesn't address the needs of the Neandertals. If you want a narrow column, you just reduce the size of your window! -- __Pascal Bourguignon__ http://www.informatimago.com/ "You question the worthiness of my code? I should kill you where you stand!" -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie - SOAP return message with embedded ZIP file
Rodney schrieb: > Hi again, thanks for the help with figuring out how to parse a SOAP return > message. I know have a return message that has an embedded ZIP file in it. > Can anyone help me figure out how to extract this file from the SOAP return > message. The message looks as following: You've been told before, you'd be told it again and again: use SOAPpy or ZSI to dela with webservices. Then you don't have to bother, yoou just _get_ the ZIP-File (as string of course) Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
[EMAIL PROTECTED] wrote: > Thomas Heller wrote: > >>X=' _ _ _ | _| _ |_|_' >>Y=0x23018F406A3530EC273F008 >>j="".join >>seven_seg=lambda n:j(j(c)+"\n"for c in zip(*[X[Y>>m+int(d)*9&7::8]for d in n >>for m in(6,3,0)])) > > > Interesting bit: > > Although there are more 3-char combinations when you read vertically, > they compact better. > > If A=" ", B="_" and C="|", this 12 char string contains al possible > combinations: > > BBBABAAACACC > > which is 2 chars shorter than the best for horizontal combinations: > > ABAAACBABCBCAC > > Still, I don't think this vertical idea can go below 123 or 124, but > it's good :-) > > Now I wonder what the 119 solution is! > I suppose the known 120 solution twisted to work with a one byte shorter string as you already found it out providing one example of it above, right? :-) Claudio -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
For the few that might be interested, I will be posting the details of a 117 character long solution to the challenge on my blog http://aroberge.blogspot.com/. Enjoy! André -- http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
David Wahler wrote: > > Not only is this obnoxious, it doesn't even work. > > Not only is this _extremely_ obnoxious, but it doesn't even work. Don't > expect any help from me. > Thanks for pointing that out (I must've missed those two examples when I read the code). And I even pointed him in a direction... apologetically-y'rs, --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
André wrote: > For the few that might be interested, I will be posting the details of > a 117 character long solution to the challenge on my blog > http://aroberge.blogspot.com/. > > Enjoy! You took advantage of prime numbers, enabling you to extract encoded information using a single modulus operation rather than shift and mask. Brilliant strategy. Congratulations. Shane -- http://mail.python.org/mailman/listinfo/python-list
compare dictionary values
What's a good way to compare values in dictionaries? I want to find values that have changed. I look for new keys by doing this: new = [k for k in file_info_cur.iterkeys() if k not in file_info_old.iterkeys()] if new == []: print new, "No new files." else: print new, "New file(s)!!!" My key-values pairs are filepaths and their modify times. I want to identify files that have been updated or added since the script last ran. Thanks, rbt -- http://mail.python.org/mailman/listinfo/python-list
Re: oop in python
Larry Bates wrote:
> novice wrote:
> > hello over there!
> > I have the following question:
> > Suppose I created a class: class Point:
> > pass
> > then instanciated an instance: new = Point()
> > So now how to get the instance new as a string: like ' new ' ; Is
> > there any built in function or method
> > for eg:
> >
> > class Point:
> >def _func_that_we_want_(self):
> > return ...
> > new._func_that_we_want_() ---> ' new '
> >
>
> Just a wild guess, but I think he wants to refer to it by a
> name. The best way to do this is to put the class instance
> in a dictionary and make the key 'new'
>
> instancedict={}
> instancedict['new']=Point()
>
> then you can call methods by:
>
> instancedict['new'].somemethod()
>
> -Larry Bates
Maybe it's more in the way of the builtin function *eval*...
example (you decide if this is what you mean ;-) )
>>> class toto(object):
... def max(self):
... return 12
...
>>> t=toto()
>>> eval("t.max")
>
>>> eval("t.max()")
12
--
http://mail.python.org/mailman/listinfo/python-list
Re: oop in python
(addendum) ... And even ...
>>> eval("t").max()
12
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Tuning a select() loop for os.popen3()
Hi all...
I've written a class to provide an interface to popen; I've included
the actual select() loop below. I'm finding that "sometimes" popen'd
processes take "a really long time" to complete and "other times" I
get incomplete stdout.
E.g:
- on boxA ffmpeg returns in ~25s; on boxB (comparable hardware,
identical OS) ~5m.
- ``ls'' on a directory with 15 nodes returns full stdout; ``ls -R''
on that same directory (with ~32K nodes beneath) stops after
4097KB of output.
The code in question is running on Linux 2.6.x; no cross-platform
portability desired. popen'd commands will never be interactive; I
just wanna read stdin/stdout and perhaps feed a one-shot string via
stdin.
Here's the relevent code (stripped of comments and various OO
setup/output stuff):
# # ## ### # # #
# cut here
def run(self):
import os, select, syslog
(_stdin, _stdout, _stderr) = os.popen3(self.command)
stdoutChunks = []; stderrChunks = []
readList = [_stdout, _stderr];
if self.stdinString is not "": writeList = [_stdin]
else: writeList = []
readStderr = False; readStdout = False
i = 0
while True:
i += 1
(r, w, x) = select.select(readList, writeList, [], 1)
read = ""
if self.stdinString is not "":
if w:
bytesWritten = os.write(_stdin.fileno(), self.stdinString)
writeList.remove(_stdin)
_stdin.close()
continue
if r:
if _stderr in r:
readStderr = True
read = os.read(_stderr.fileno(), 16384)
if read: stderrChunks.append(read)
else:readList.remove(_stderr)
continue
elif _stdout in r:
readStdout = True
read = os.read(_stdout.fileno(), 16384)
if read:
stdoutChunks.append(read)
syslog.syslog("Command instance read %d from stdout" % len(read))
else:readList.remove(_stdout)
continue
else:
if \
(readStderr and self.dieOnStderr) \
or \
readStdout:
syslog.syslog("Command instance finished")
break
return
# cut here
# # ## ### # # #
Tweaking (a) the os.read() buffer size and (b) the select() timeout
and testing with ``ls -R'' on a directory with ~ 32K nodes beneath, I
find the following trends:
1. With a very small os.read() buffer, I get full stdout, but running
time is rather long. Running time increases as select() timeout
increases.
2. With a very large os.read() buffer, I get incomplete stdout (but
running time is *very* fast). As select() timeout increases, I get
better and better results - with a select() timeout of 0.2 I seem to
get reliably full stdout.
The values used in the code I've pasted above - large buffer, large
select() timeout - seem to perform "well enough"; none of the
previously described problems manifest. However, ``ls -lR /'' (way
more than 32K nodes) "sometimes" gives incomplete stdout.
My first question, then, is paranoid: I've run all these benchmarks
because the application using this code saw a HUGE performance hit
when we started using popen'd commands which generated "lots of"
output.
Is there anything wrong with the logic in my code?!
Will I see severe performance degradation (or worse, incomplete
stdout/stderr) as system variables change (e.g. system load increases,
popen'd program changes, popen'd program increases workload, etc.)?
Next question - how do I tune the select() timeout and the os.read()
buffer correctly? Is it *really* per- command, per- system, per-
phase-of-moon voodoo? Is there a Reccommended Setup for such a
select() loop?
Thanks in advance, for insight as well as for tolerating my
long-windedness...
--
Christopher DeMarco <[EMAIL PROTECTED]>
Alephant Systems (http://alephant.net)
PGP public key at http://pgp.alephant.net
+1-412-708-9660
signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Shane Hathaway wrote: > André wrote: > >>For the few that might be interested, I will be posting the details of >>a 117 character long solution to the challenge on my blog >>http://aroberge.blogspot.com/. >> >>Enjoy! > > > You took advantage of prime numbers, enabling you to extract encoded > information using a single modulus operation rather than shift and mask. > Brilliant strategy. Congratulations. Indeed. Very impressive. And thanks for posting, it was driving me nuts. Now I wonder if this could be adapted to the other, three loop strategy? It's not clear, but there are three characters that are superfulous in the current incarnation of that. Hmmm.. -tim -- http://mail.python.org/mailman/listinfo/python-list
Re: csrss.exe & Numeric
jelle wrote: > I have a function that uses the Numeric module. When I launch the > function csrss.exe consumes 60 / 70 % cpu power rather than having > python / Numeric run at full speed. Has anyone encountered this problem > before? It seriously messes up my Numeric performance. > Are you memory-limited so that the process is swapping memory to disk? We'll need more details to offer a better suggestion. Best, -Travis -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Tech Geekers and their Style
[followups to comp.infosystems.www.authoring stylesheets, since that's the only newsgroup the OP addressed where this is relevant (LISP?? what was he thinking?] Xah Lee wrote: > Sometimes you want your text to flow into multiple columns, as in > newspaper's layout. However, as of 2005-12 this is not yet possible. > One can make-do by hard-coding it into HTML TABLE using multiple > columns. It is a pain because when you change your text, you have to > manually cut and paste to justify each and every columns by > trial-n-error. It's also pointless since that balances the text only in *your* browser, using your settings. It will look unbalanced in other people's browsers. > > A proposed solution is in CSS3 “Multi-column layout”, drafted in > 2001 but not yet in any mainstream browsers as of 2005-12. See > http://www.w3.org/TR/2001/WD-css3-multicol-20010118/ > > With all the whizbang of styles and features in CSS2, a basic, > necessary, functional layout feature as multi-columns is not there yet. > This is a indication of the fatuousness of the IT industry's > technologies and its people. It isn't either basic or (obviously, since the world is still turning after all these years without it) necessary. -- http://mail.python.org/mailman/listinfo/python-list
Re: csrss.exe & Numeric
[jelle] > I have a function that uses the Numeric module. When I launch the > function csrss.exe consumes 60 / 70 % cpu power rather than having > python / Numeric run at full speed. Has anyone encountered this problem > before? It seriously messes up my Numeric performance. > > I'm running 2.4.2 on xp. Need more clues than that. What does your function do? What facilities does your function make use of? csrss.exe is the "user-mode side" of Windows, and consumes a lot of CPU if, for example, you're starting/stopping many threads, or display a lot of output to "a DOS box". You should also be aware that several kinds of malware install a program named "csrss.exe" or "CSRSS.EXE" (search the web for more on that, and run a virus scan). -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
André wrote: > For the few that might be interested, I will be posting the details of > a 117 character long solution to the challenge on my blog > http://aroberge.blogspot.com/. > > Enjoy! > > André > It doesn't work for me as described on that page. The output is scrumbled. It seems, that the 12 bytes long string ' _ |_|_ _| |' is the reason, as the index [11] to it gives '|' not the expected '| |'. There are a total of 24 following 14 bytes strings possible for use in coding of indexes to all necessary character triples: ' | |_ _ _|_|' ' | |_|_ _ _|' ' |_ _ _| |_|' ' |_ _ _|_| |' ' |_| |_ _ _|' ' |_|_ _ _| |' ' _ | |_ _|_|' ' _ | |_|_ _|' ' _ |_ _| |_|' ' _ |_ _|_| |' ' _ |_| |_ _|' ' _ |_|_ _| |' ' _ _| |_ |_|' ' _ _| |_|_ |' ' _ _|_ | |_|' ' _ _|_ |_| |' ' _ _|_| |_ |' ' _ _|_|_ | |' ' _| |_ _ |_|' ' _| |_|_ _ |' ' _|_ _ | |_|' ' _|_ _ |_| |' ' _|_| |_ _ |' ' _|_|_ _ | |' so I tried all which made sense in the context of '0' conversion and found out, that it should be the ' _ |_|_ _| |' not the at http://aroberge.blogspot.com/ ' _ |_|_ _| |' given one to make the described algorithm work as expected. Anyway, the code with the two bytes longer string is 117 bytes long, so the announcement of a 117 bytes long code keeps what it promises. Excellent work! What I wonder about is, how the author arrived at that solution? Trying all of the 24 available 14 byte strings to see which one produces the coding table which can be used as it was used? Trial-and-error over using division, modulo, shifting, masking? What was the path of thought to arrive at that? Knowing the solution seems to be of little value if not knowing how to arrive at it when a similar problem comes up in the future. Claudio P.S. By the way: on Windows XP with UltraEdit there was no problem to input the special characters. There is an ASCII table and a HEX editor mode available for it. Any hints which free editor makes it possible, too? -- http://mail.python.org/mailman/listinfo/python-list
Re: compare dictionary values
In <[EMAIL PROTECTED]>, rbt wrote: > What's a good way to compare values in dictionaries? Look them up and then compare!? ;-) > I want to find > values that have changed. I look for new keys by doing this: > > new = [k for k in file_info_cur.iterkeys() if k not in > file_info_old.iterkeys()] > if new == []: > print new, "No new files." > else: > print new, "New file(s)!!!" > > My key-values pairs are filepaths and their modify times. I want to > identify files that have been updated or added since the script last ran. This looks up each `key` from the `new` dictionary and compares the value with the `old` one. If it's not equal or the key is not present in `old` the key is appended to the `result`:: def new_and_changed_keys(old, new): result = list() for (key, value) in new: try: if old[key] != value: result.append(key) except KeyError: result.append(key) return result Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Claudio Grondi wrote: > so I tried all which made sense in the context of '0' conversion and > found out, that it should be the > >' _ |_|_ _| |' > > not the at http://aroberge.blogspot.com/ > >' _ |_|_ _| |' The HTML source has the three spaces. If the code had been surrounded by a "pre" tag, it would have rendered correctly. Shane -- http://mail.python.org/mailman/listinfo/python-list
Re: compare dictionary values
Marc 'BlackJack' Rintsch wrote: > In <[EMAIL PROTECTED]>, rbt wrote: > >> What's a good way to compare values in dictionaries? > > Look them up and then compare!? ;-) > >> I want to find >> values that have changed. I look for new keys by doing this: >> >> new = [k for k in file_info_cur.iterkeys() if k not in >> file_info_old.iterkeys()] >> if new == []: >> print new, "No new files." >> else: >> print new, "New file(s)!!!" >> >> My key-values pairs are filepaths and their modify times. I want to >> identify files that have been updated or added since the script last ran. > > This looks up each `key` from the `new` dictionary and compares the value > with the `old` one. If it's not equal or the key is not present in `old` > the key is appended to the `result`:: > > def new_and_changed_keys(old, new): > result = list() > for (key, value) in new: > try: > if old[key] != value: > result.append(key) > except KeyError: > result.append(key) > return result > > Ciao, > Marc 'BlackJack' Rintsch Thanks Marc! I changed this line: for (key, value) in new: To this: for (key, value) in new.iteritems(): And, it works great. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido working on Pypy?
"Andrew Durdin" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] On 29 Dec 2005 04:12:53 -0800, Luis M. González <[EMAIL PROTECTED]> wrote: |> |> According to this blog entry, it says that Guido has been hired by |> Google to work on Pypy: |> http://zephyrfalcon.org/weblog2/arch_e10_00870.html |> |> Is there anyone who can confirm this information? |> Luis |Or deny it: | |http://zephyrfalcon.org/weblog2/arch_e10_00870.html#e872 | |Andrew Well, apparently Guido himself did take the time to deny the claims regarding PyPy made in this article. http://www.computable.nl/nieuws.htm?id=1039941&WT.mc_id=rss#reacties (see the section lower on the page). For those unfamiliar with Dutch, his reaction translates into English as follows: "This is largely nonsense -- I indeed work for Google but I am not involved in PyPy, and the same applies to Google. In addition, PyPy is not being developed "on behalf of the EU" but is subsidized by the EU. See http://codespeak.net/pypy/dist/pypy/doc/news.html for more info on PyPy." Regards, Vincent Wehren -- http://mail.python.org/mailman/listinfo/python-list
Re: Python as a Server vs Running Under Apache
as great as mod_python is, there are lots of restrictions and limitations to what youc an do with it because of limitations of apache itself, and I am refereing to apache 2.x as well as 1.x, like others are saying if you don't need apache specific things it will just be one more thing to work around the design constraints it causes, twisted will be you best bet -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Shane Hathaway wrote: > Claudio Grondi wrote: > > so I tried all which made sense in the context of '0' conversion and > > found out, that it should be the > > > >' _ |_|_ _| |' > > > > not the at http://aroberge.blogspot.com/ > > > >' _ |_|_ _| |' > > The HTML source has the three spaces. If the code had been surrounded > by a "pre" tag, it would have rendered correctly. > > Shane Thanks, I hadn't noticed that. It should be fixed now. André -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Claudio Grondi wrote: > > P.S. By the way: on Windows XP with UltraEdit there was no problem to > input the special characters. There is an ASCII table and a HEX editor > mode available for it. Any hints which free editor makes it possible, too? I simply used Pythonwin. (print chr(3), then cut and paste the result in my python file). André -- http://mail.python.org/mailman/listinfo/python-list
Re: compare dictionary values
In <[EMAIL PROTECTED]>, rbt wrote:
> What's a good way to compare values in dictionaries?
Do you need to compare dictionaries, if its an option it would be
simpler/cheaper to compare each entry from your file
listing with entries in a single dict and act accordingly, mainly
because you will already have built your path/date pairs from your dir
listing, adding them to a dict purely for comparison is an extra
step.
import os
new_files = [ ]
changed = [ ]
listing = os.listdir('c:/python24')
for a_file in listing:
f_date = os.path.getmtime(os.path.join('c:/python24' , a_file))
try
if mydict[a_file] != f_date:
changed.append(a_file)
except:
new_files.append(a_file)
mydict[a_file] = f_date
deleted = [ key for key in mydict if not key in listing ]
for x in deleted:
del mydict[x]
print changed
print new_files
print deleted
HTH :)
--
http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
I managed it with vim. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Robert Kern <[EMAIL PROTECTED]> writes: [...] > No, it's not a silly idea. Dean Baker, the Co-Director the Center for Economic > and Policy Research, has proposed for the U.S. government to establish a > Software Developer's Corps. For $2 billion per year, it could fund about > 20,000 > developers to make open source software. Much of that software would be > directly > usable by local, state, and federal governments and thus pay back some, all, > or > more of the investment (Dean estimates more). In addition, the general public > also benefits directly. > > http://www.cepr.net/publications/windows_2005_10.pdf Given the current balance of power in the USA government, I assume this proposal is aimed at >= 2008 ;-) John -- http://mail.python.org/mailman/listinfo/python-list
Global Variables in OOP and Python
Hello, I have questions about global variables in OOP (in general) and Python (in specific). I understand (I think) that global variables are generally not a good idea. However, if there are variables that need to be accessed by a number of classes that exists in separate namespaces (files), what would be the best way to do this? So far, I have approached the problem by making the variables attributes of one class and passing instances of the class as variables to the other class' methods. The other way I thought of is to create a separate class that consists of the variables and to use the from import * in all of the files (namespaces) where it is needed. Is there a better way? Are the two ideas presented above acceptable? If so, is one better than the other from an OOP POV? -- http://mail.python.org/mailman/listinfo/python-list
python encoding bug?
I was playing with python encodings and noticed this:
[EMAIL PROTECTED]:~$ python2.4
Python 2.4 (#2, Dec 3 2004, 17:59:05)
[GCC 3.3.5 (Debian 1:3.3.5-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> unicode('\x9d', 'iso8859_1')
u'\x9d'
>>>
U+009D is NOT a valid unicode character (it is not even a iso8859_1
valid character)
The same happens if I use 'latin-1' instead of 'iso8859_1'.
This caught me by surprise, since I was doing some heuristics guessing
string encodings, and 'iso8859_1' gave no errors even if the input
encoding was different.
Is this a known behaviour, or I discovered a terrible unknown bug in python
encoding
implementation that should be immediately reported and fixed? :-)
happy new year,
--
---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
--
http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
LMFAO! those were jokes for my friends. lol.and btw the dccpoper and bot and crap were jokes that i made up for my friends on the #python channel in freenode... It was a joke.Anyway.. My bad, its ok if u dont want to help... no one likes me on this group anyway... u guys just joined the crowd... btw, wat do u mean >get yourself aquainted with the language (and maybe programming in general).< Dude, why do u think im not? ive programmed many small and many big programs, if this is a noob question then my bad, ive asked many ppl and they cant answer me and this was my last resort since i knew i would get this kind of bullshit. I know most of the language fairly and im tired of coming on here and always getting pointed to python tutorials, its actually pretty annying, if you dont have a liable answer then could u please not post then, it only makes sense. Instead of telling someone that their dumb and that u dont know python, how about just help answering the question. But watever, i dont know y but this whole group just hates me... If anyone has a answer then please feel free to post(unlikely). But thx anyway.. -- http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
http://h1.ripway.com/jay001/PyIRCnMo.txt -- http://mail.python.org/mailman/listinfo/python-list
Re: Global Variables in OOP and Python
On Fri, 30 Dec 2005 15:03:54 -0800, newbie wrote:
> Hello,
>
> I have questions about global variables in OOP (in general) and Python
> (in specific). I understand (I think) that global variables are
> generally not a good idea. However, if there are variables that need to
> be accessed by a number of classes that exists in separate namespaces
> (files), what would be the best way to do this?
>
> So far, I have approached the problem by making the variables
> attributes of one class and passing instances of the class as variables
> to the other class' methods.
Do you mean something like this?
# Module care_and_feeding
import birds
import foods
def feed_my_pet():
pet = birds.Parrot("Norwegian Blue")
snack = foods.Spam("A tasty meat-like treat")
pet.eats(snack)
return "Yummy!"
That is a good way of handling the problem.
> The other way I thought of is to create a separate class that consists
> of the variables and to use the
>
> from import *
>
> in all of the files (namespaces) where it is needed.
That's a bad way of handling it. It has all the worst aspects of using
global variables, plus the worst aspects of import * (namespace pollution
and shadowing of existing names).
Unless I'm badly mistaken, Guido has decided that "from module import *"
was a mistake, and that will be removed from the (legendary) Python 3, if
and when it gets created. In the meantime, it is highly recommended that
you don't use that form.
> Is there a better way?
>
> Are the two ideas presented above acceptable? If so, is one better than
> the other from an OOP POV?
I think the first way is fine, but of course the Devil is in the details:
I can't judge your code without seeing it.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
generators in Java?
This may have been discussed before, so I apologize. Does Java have generators? I am aware of the "Iterator" interface, but it seems much more restrictive. Python generators are useful for many more things than simply list enumeration, but the Java Iterator seems limited. Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
Jay wrote: > LMFAO! Yeah, me too. How lame do you think we are?! --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
Heiko Wundram wrote: > Yeah, me too. How lame do you think we are?! I won't feed the trolls... I won't feed the trolls... I won't feed the trolls... I won't feed the trolls... --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Strange interaction between exec, dictionary subtypes, and global variables in 2.4
I've been playing with dictionary subtypes for custom environments, and I encountered a strange interaction between exec, dictionary subtypes, and global variables. I've attached a test program, but first I'd like to give some background. Python uses dictionary objects as symbol tables in it's execution contexts. Since these objects used to be basic types, which were not subclassable, some of the interpreter code accessed them using low-level C functions. Then dictionary types were made subclassable, and I was pretty excited, because I wanted to use them to set up custom execution environments with extended semantics. This didn't work, because when the dictionary types were made subclassable, the interpreter code which used them as symbol tables was not changed, so subclassed dictionaries used in exec statements or eval calls bypassed their subclass functions, and jumped straight to the underlying C functions. In python 2.4, this was finally fixed, and you can now use subclassed dictionaries in exec statements and eval calls. Except that there is some niggling edge case dealing with variables which have been marked 'global'. It seems that if a compiled chunk of python contains a 'global VAR' statement, anywhere, then that VAR, and only that VAR, will bypass the subclassed functions when it is accessed. I'd like to fix this, and send it upstream, and I've worked on extensive python/C bindings before, but I've not hacked the interpreter. I took a look around, and I'm not sure where the symtable lookup is happening. However, I have some belief that someone on this list _may_ be able to point me in the right direction. #!/usr/bin/python2.4 class TypedDictionary(dict): def __setitem__(self, key, value): print '__setitem__(%s, %s)' % (key, value) if self.has_key(key): t = type(self[key]) try: value = t(value) except Exception: raise TypeError, \ "illegal assignment to '%s': %s cannot be coerced to %s" \ % (key, type(value), t) dict.__setitem__(self, key, value) test_script = """ foo = 0 bar = 'xyz' print 'foo:', repr(foo), '; bar:', repr(bar) foo = '1' bar = 42 print 'foo:', repr(foo), '; bar:', repr(bar) """ print "Without 'global foo':" exec test_script in TypedDictionary() print print "With 'global foo':" exec test_script + """ def f(): global foo pass """ in TypedDictionary() This program produces this output: Without 'global foo': __setitem__(foo, 0) __setitem__(bar, xyz) foo: 0 ; bar: 'xyz' __setitem__(foo, 1) __setitem__(bar, 42) foo: 1 ; bar: '42' With 'global foo': __setitem__(bar, xyz) foo: 0 ; bar: 'xyz' __setitem__(bar, 42) foo: '1' ; bar: '42' __setitem__(f, ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Global Variables in OOP and Python
"newbie" <[EMAIL PROTECTED]> writes:
> So far, I have approached the problem by making the variables
> attributes of one class and passing instances of the class as variables
> to the other class' methods.
That's the standard way to do it in OO languages.
> The other way I thought of is to create a separate class that consists
> of the variables and to use the
>
> from import *
>
> in all of the files (namespaces) where it is needed.
Except for one detail, this is a Pythonesque method. The detail is
that "from import *" is generally considered a bad
idea. There are two reasons for this:
1) Blindly adding everything in a module to your namespace is liable
to cause collisions. If the module you're doing this to is stable,
this isn't much of a problem.
2) It makes finding where a variable came from harder. Having to
search extra modules for globals is a pain. If the exported names have
a prefix on them to identify the module, that goes away. But in that
case, you might as well do "import as ", and leave
the prefix off the variable names in the module.
A better way to do this is to give your module a name that denotes
it's function ("config", for instances, or maybe even "globals") and
use that.
> Are the two ideas presented above acceptable? If so, is one better than
> the other from an OOP POV?
With the one change, they are. From an OO point of view, they're
almost identical. In Python, a module is an object, so the difference
is whether you want to instantiate a custom class to hold your
globals, or use the builtin module type for that purpose.
http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
--
http://mail.python.org/mailman/listinfo/python-list
List index method for complex list item types?
I'm a Python newbie who just started learning the language a few weeks ago. So these are beginner questions. I have a list of sockets that I use for select.select calls like this: ReadList,WriteList,EventList = select.select(self.SocketList,[],[],3) In parallel with that list of sockets I want something that is like a list of socket,PacketFragment pairs. I need this because I could do recv and get part of a sent packet. I want to loop around and each time add more to the fragment until I get a full packet which has an internal byte structure of the types I'm expecting. The idea is every time I do self.SocketList.append(NewSocket) also do self.SocketPacketFragmentList.append((NewSocket,'')) so that the index into SocketList is the same as the index into SocketPacketFragmentList. So I can use self.SocketList.index(SomeSocket) find an item in SocketList and then know how to find it in the other list. MySocketIndex = self.SocketList.index(MyTargetSocket) Then do: MySubList = self.SocketPacketFragmentList[MySocketIndex] Then MyPacketFragment = MySubList[1] But a thought struck me while writing this: Does Python not provide a way to search a list of sublists to find something on, say, the value of the first sublist item field as a way to find the index to the item one wants in the parent list? There does not appear to be an alternative to lists that has better functionality for this purpose. Dictionaries are immutable, right? One can't use dictionaries for doing look-ups on dynamically changing lists? For efficiency's sake it seems to me one wants a search function on lists that returns two things: - index where the item found. - full item which matches on the particular field one is looking up on. Am I wrong in thinking Python doesn't really provide an automated way to search lists of complex things? Also, ii C++ one can use STL iterators to move thru a list or deque. But if one needs to advance thru a list with array indexes that does Python index in each time if one is looping thru the list? In Python maybe the trick is to use ii = 0 For item in List # see if item matches ii = ii + 1 and then somehow pop out of the for loop once one finds a match? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuning a select() loop for os.popen3()
In article <[EMAIL PROTECTED]>, Christopher DeMarco <[EMAIL PROTECTED]> wrote: > I've written a class to provide an interface to popen; I've included > the actual select() loop below. I'm finding that "sometimes" popen'd > processes take "a really long time" to complete and "other times" I > get incomplete stdout. ... > My first question, then, is paranoid: I've run all these benchmarks > because the application using this code saw a HUGE performance hit > when we started using popen'd commands which generated "lots of" > output. > > Is there anything wrong with the logic in my code?! I tried a modified version with 'ls -R .', which yields about 1 Mb of data, and saw no problems on MacOS X. Same data, and about the same time as 'ls -R .' from the shell, maybe 5% longer. But I modified it a lot. I removed every "continue", I removed the "break", and I made readList the condition for the while loop. With these changes, a 0.1 second timeout is about the same as no timeout, but at 0.01 second I do see a little slow down. Still no loss of data. I suspect there is indeed something wrong with your logic, but I'm not going to try to figure it out. If you're sure it's right, I think you should post again with the actual code for a program that demonstrates your problem(s). Your goal for the revised logic should be 1) avoid gratuitous branches in the flow of control, 2) reduce number of state variables that you have to account for, and 3) express your intentions clearly with respect to the timeouts -- what do you do when it times out, and why? Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: IRC sockets and queries
kk -- http://mail.python.org/mailman/listinfo/python-list
python coding contest
Here's a variant of André's brilliant idea that's
119 characters long, and fully printable:
j=''.join;seven_seg=lambda z:j(j(' _ | |_ _|_|'
[ord('^r|=Zm.:v\r'[int(a)])%u*2:][:3]for a in z)
+"\n"for u in(3,7,8))
Mark
--
http://mail.python.org/mailman/listinfo/python-list
Re: Global Variables in OOP and Python
newbie wrote: >Hello, > >I have questions about global variables in OOP (in general) and Python >(in specific). I understand (I think) that global variables are >generally not a good idea. However, if there are variables that need to >be accessed by a number of classes that exists in separate namespaces >(files), what would be the best way to do this? > >So far, I have approached the problem by making the variables >attributes of one class and passing instances of the class as variables >to the other class' methods. > >The other way I thought of is to create a separate class that consists >of the variables and to use the > >from import * > > That form is deprecated. Better (and certainly clearer to any reader of the code) is to leave them in the module. Define a module, say Parameters, that defines any number of variables containing useful values. Then import Parameters wherever you want and refer to Parameters.a and Parameters.b You can even add runtime parameters (say options and paths from the command line) to the module during your initialization code, and those will be available wherever Parameters is imported: Parameters.xyzzy = 'whatever' Parameters.startDirectory = os.getcwd() # Get working directory at startup (Even if the import of Parameters in some file occurs before the initialization code has a chance to run.) Gary Herron >in all of the files (namespaces) where it is needed. > >Is there a better way? > >Are the two ideas presented above acceptable? If so, is one better than >the other from an OOP POV? > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: List index method for complex list item types?
[EMAIL PROTECTED] writes: > I have a list of sockets that I use for select.select calls like this: [...] > But a thought struck me while writing this: Does Python not provide a > way to search a list of sublists to find something on, say, the value > of the first sublist item field as a way to find the index to the item > one wants in the parent list? No, it doesn't. It's not hard to write, though. ISTR something about list methods growing optional arguments that might be usable for this in 2.5, but you'd have to check it yourself. But a list is the wrong tool to use for this problem. > There does not appear to be an alternative to lists that has better > functionality for this purpose. Dictionaries are immutable, right? One > can't use dictionaries for doing look-ups on dynamically changing > lists? Dictionaries are mutable. But you could still use them this way. > For efficiency's sake it seems to me one wants a search function on > lists that returns two things: >- index where the item found. >- full item which matches on the particular field one is looking up > on. Indexing into a list is fast, so there's no really not much need for this. > Am I wrong in thinking Python doesn't really provide an automated way > to search lists of complex things? No, you're not wrong. But using lists is the wrong way to solve your problem. > Also, ii C++ one can use STL iterators to move thru a list or deque. > But if one needs to advance thru a list with array indexes that does > Python index in each time if one is looping thru the list? > > In Python maybe the trick is to use > ii = 0 > For item in List > # see if item matches > > ii = ii + 1 > > and then somehow pop out of the for loop once one finds a match? Use "break" to pop out of the list. Use "enumerate" to iterate through both the list and an index into the list. However, for your problem - finding data associated with a socket that you're using in a select - a list is the wrong tool. Sockets are usable as dictionary keys. So you can store arbitrary extra data in a dictionary indexed by the sockets. That will be faster than searching a list, even if the comparison is very simple. Alternatively, subclass socket, add the data you want associated with each socket to the instances of the subclass, and pass select instances of your subclass. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
