Re: a problem to solve
[EMAIL PROTECTED] wrote: > If you need help in figuring out how to walk through all 4096 possible > switch sets, just ask. Ok, thanks to your list, I figured out a program that works! It's probably not the best, and it doesn't really display which switches are correct in any apparent way (you have to look for them in the list), but it works! Here's the code. I'd love to see your implementation too. from gmpy import digits panelOne = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] panelTwo = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] panelThree = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] panelFour = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] for a in panelOne: for b in panelTwo: for c in panelThree: for d in panelFour: if (a & b & (c ^ d)) | (c & d & (a ^ b)) == 1048575: print 'Solution is:', digits(a, 16), digits(b, 16), digits(c, 16), digits(d, 16) raw_input() -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
[EMAIL PROTECTED] wrote: > John Salerno wrote: >> John Salerno wrote: >>> [EMAIL PROTECTED] wrote: >>> No. First of all, combining them with the & operator would be the asnswer to having all four lamps lit in the same position. But you want exactly 3 (in any combination). The correct way to combine the switches (using my answer of a[7] b[2] c[5] d[3]) is to use the boolean expression I gave you initially: >>> Ah, that makes sense. I think I have a handle on it now. Of course, you >>> did the grunt work of making the hex list, which might not have been so >>> fun, but now I can work on using it to get the solution. Once I do, I'd >>> love to compare my answer to yours, because something tells me yours >>> will be much more elegant. :) >> p.s. is there an xor operator in python? > > Yep. The XOR operator is ^. That's why you have to use ** > for exponentiation. In addition to &=AND, there is also > |=OR. I actually gave two boolean expressions. > > First, using the standard notation, where concatenation implies > AND, + is OR and x is XOR (actually, the standard notation > for XOR is a + inside a circle, but my keyboard doesn't have > one of those). > > Y = CD(A x B) + AB(C x D) > > Second, using the Python operators > > Y = ((C & D) & (A ^ B)) | ((A & B) & (C ^ D)) > Thanks! Back to work for me! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > John Salerno wrote: > > [EMAIL PROTECTED] wrote: > > > >> No. First of all, combining them with the & operator would be > >> the asnswer to having all four lamps lit in the same position. > >> But you want exactly 3 (in any combination). The correct way > >> to combine the switches (using my answer of a[7] b[2] c[5] d[3]) > >> is to use the boolean expression I gave you initially: > > > > Ah, that makes sense. I think I have a handle on it now. Of course, you > > did the grunt work of making the hex list, which might not have been so > > fun, but now I can work on using it to get the solution. Once I do, I'd > > love to compare my answer to yours, because something tells me yours > > will be much more elegant. :) > > p.s. is there an xor operator in python? Yep. The XOR operator is ^. That's why you have to use ** for exponentiation. In addition to &=AND, there is also |=OR. I actually gave two boolean expressions. First, using the standard notation, where concatenation implies AND, + is OR and x is XOR (actually, the standard notation for XOR is a + inside a circle, but my keyboard doesn't have one of those). Y = CD(A x B) + AB(C x D) Second, using the Python operators Y = ((C & D) & (A ^ B)) | ((A & B) & (C ^ D)) -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > [EMAIL PROTECTED] wrote: > >> No. First of all, combining them with the & operator would be >> the asnswer to having all four lamps lit in the same position. >> But you want exactly 3 (in any combination). The correct way >> to combine the switches (using my answer of a[7] b[2] c[5] d[3]) >> is to use the boolean expression I gave you initially: > > Ah, that makes sense. I think I have a handle on it now. Of course, you > did the grunt work of making the hex list, which might not have been so > fun, but now I can work on using it to get the solution. Once I do, I'd > love to compare my answer to yours, because something tells me yours > will be much more elegant. :) p.s. is there an xor operator in python? -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP for nondeterminism.
"Adam DePrince" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] I think this should have better been posted to comp.lang.python My reletively short answer should explain why. >I frequently find myself in a situation where I wish I could say "the > execution order of these two lines just doesn't matter." Having been 'raised' on Dijkstra's non-deterministically ordered guarded statememts, I have a certain amount of sympathy, however > Proposed here are two freshly drafted PEP's advocating for the addition > of nondeterminism as a spring board for future automatic parallelism. > > The first calls for core language changes, the second calls for a minor > (and likely symbolic) change to list comprehension's semantics to better > support future parallelism. these two proposals strick me as premature, since currently irrelevant to the overwhelming majority of users, misdirected, since they probably will not solve future problems, and out-of-date, since they obsoleted by what can be and is being done today with no change to the language. >any retval: >1 >2+3 >my_function_that_returns_17() >... > >retval would be assigned [1, 5, 17] Only the order of evaluation >is not deterministic. This should not be a statement, but can be and should be a function. By current trends, it should specifically be a generator function , coded in C or calling C helper functions for some particular parallel hardware, which does perhaps the following: def anyorder(*funcs): while funcs: yield # and remove corresponding func from funcs >first retval: > urllib.open( 'mirror1' ).read() > urllib.open( 'mirror2' ).read() > urllib.open( 'mirror3' ).read() > > >retval would contain the data from the fastest mirror, the other >threads would be disposed of. Even more obviously a function. def firstreturn(*funcs): return >We change the semantics of a the list comprehension to >explicitly state that the order of evaluation is >non-deterministic, and that there should exist no dependencies or >side effects. This leaves open the potential for future >parallelization. Silly to me because 0) Only people who need non-determinism should be concerned about it. 1) The order *is* deterministic and will be for CPython for at least 2.X and probably 3.X, and hence the false claim will be ignored and/or laughed at. 2a) Many list operations and iterators are potentially parallel, not just list comps. Indeed, list comps combine and can be rewritten as map and filter which can, when possible and appropriate, be replaced with parallel versions now. No 'symbolic' declaration needed. 2b) For another example, Google uses a proprietary map_reduce function (in C, with Java, Python, and perhaps other wrappers) to run map followed by reduce in parallel on thousands of machines in their proprietary server plantations. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie parsing question
"Kun" wrote: > i tried to parse (below) with the regular expression: emails = > re.findall('\S*\s([EMAIL PROTECTED])', senders) > > and got the following error: > > Traceback (most recent call last): >File "/Life/School/Homework/Spring 2006/OPIM > 399/Tutorial/IMAP/scannermailer.py", line 19, in -toplevel- > emails = re.findall('\S*\s([EMAIL PROTECTED])', senders) >File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre.py", > line 167, in findall > return _compile(pattern, flags).findall(string) > TypeError: expected string or buffer > > any help would be appreciated. findall expects a string as the target, not a list of strings. you can either use a loop to apply the RE to each string fragment separately, or join the fragments into a single string before you pass it to re.findall. on the other hand, your data looks pretty regular. why not just loop over the fragments and look for things that start with "From:" ? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I handle #
Michael Sperlle wrote: > I need to write out a file containing the # comment. When I try to specify > it as part of a literal, everything afterward turns into a comment. "turns into a comment" in what sense ? from your description, it sounds like a bug in your editor's syntax highlighter. Python itself definitely won't look for comment markers inside string literals. -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding problems (é and è)
Jean-Paul Calderone wrote: > On Fri, 24 Mar 2006 09:33:19 +1100, John Machin <[EMAIL PROTECTED]> wrote: > >On 24/03/2006 8:36 AM, Peter Otten wrote: > >> John Machin wrote: > >> > >>>You can replace ALL of this upshifting and accent removal in one blow by > >>>using the string translate() method with a suitable table. > >> > >> Only if you convert to unicode first or if your data maintains 1 byte == 1 > >> character, in particular it is not UTF-8. > >> > > > >I'm sorry, I forgot that there were people who are unaware that > >variable-length gizmos like UTF-8 and various legacy CJK encodings are > >for storage & transmission, and are better changed to a > >one-character-per-storage-unit representation before *ANY* data > >processing is attempted. > > Unfortunately, unicode only appears to solve this problem in a sane manner. What problem do you mean? Loose matching is solved by unicode in a sane manner, it is described in the unicode collation algorithm. Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: New development windows, IronPython or PythonWin
Caleb Hattingh wrote: > Also, I think IronPython is also supported by only one guy - Jim > Hugunin. The fact that IronPython development is effectively being > sponsored by Microsoft doesn't fill me with great expectations either, > although it would be a good thing if they really supported it well. This is not completely true. IronPython is developed by the IronPython team in Microsoft, not only by Jim Hugunin. From the IronPython mailing list, at least following Microsoft employees are working on IronPython: Jim Hugunin, Dino Viehland, Martin Maly, Haibo Luo. Seo Sanghyeon -- http://mail.python.org/mailman/listinfo/python-list
PEP for nondeterminism.
I frequently find myself in a situation where I wish I could say "the execution order of these two lines just doesn't matter." Proposed here are two freshly drafted PEP's advocating for the addition of nondeterminism as a spring board for future automatic parallelism. The first calls for core language changes, the second calls for a minor (and likely symbolic) change to list comprehension's semantics to better support future parallelism. PEP: XXX Title: Nondeterminism Version: $Revision$ Last-Modified: $Date$ Author: Adam DePrince <[EMAIL PROTECTED]> Status: Draft Python-Version: 3.0 Type: Standards Content-Type: text/plain Created: 24-Mar-2006 Post-History: Abstract Proposed herein is are two new control flow structures that allow the explicit specification of parallelism by defining the order of expression evaluation as non-deterministic, thus removing the requirement of sequential execution. Background A number of mechanisms have been proposed in Python that have the side effect of permitting the automatic discovery of parallelism. PEP 288 presents the notion of a generator, an object that inherently lends itself to concurrent operation and possibility automatic self organization of a pipeline. Stackless Python in PEP 219/220 presents a mechanism by which a large number micro threads could be efficiently supported, thus allowing for a realistic manifestation of a deep generator based software pipeline. Additionally, this PEP's sibling, XXX, proposes that the execution order of list comprehensions be made non-deterministic to permit future parallel implementations. DISCUSSION Two new control flow structures are proposed. While as of yet no name is proposed, for the sake of brevity we will refer to them as any and first. The any structure would call for the execution of all expressions within the any block in an non-determinate order. The user would warrant that no side effects exist between the expressions, and assigned to the variable the any block would be a list representing the return values of each of the expressions in the order they appear in the code (but not necessarily in the order of execution.) The first structure would execute all enclosed expressions concurrently, again, the order of execution being non-deterministic, other than the promise that all would be started. The return value of the first expression to finish would be assigned to the variable associated with the first block and the execution of the other operations terminated. SPECIFICATION The use of the word 'any' and 'first' is only a convenience. I do not yet propose a keyword for these structures. ... any retval: 1 2+3 my_function_that_returns_17() ... retval would be assigned [1, 5, 17] Only the order of evaluation is not deterministic. first retval: urllib.open( 'mirror1' ).read() urllib.open( 'mirror2' ).read() urllib.open( 'mirror3' ).read() retval would contain the data from the fastest mirror, the other threads would be disposed of. IMPLEMENTATION TBD - Incomplete REFERENCES TBD COPYRIGHT This document has been placed in the public domain. PEP: XXX Title: Nondeterministic List comprehensions Version: $Revision$ Last-Modified: $Date$ Author: Adam DePrince <[EMAIL PROTECTED]> Status: Draft Python-Version: 3.0 Type: Standards Content-Type: text/plain Created: 24-Mar-2006 Post-History: Abstract The semantics of the list comprehension offer the future benefit of multi-threading and parallel execution, assuming that the programmer treat the order of evaluation as non-deterministic and avoids the introduction of dependencies and side-effects. Background A number of mechanisms have been proposed in Python that have the side effect of permitting the automatic discovery of parallelism. PEP 288 presents the notion of a generator, an object that inherently lends itself to concurrent operation and possibility of automatic self organization of pipelined, and thus parallel, operation. Stackless Python in PEP 219/220 presents a mechanism by which a large number micro threads could be efficiently supported, thus allowing for a realistic manifestation of a deep generator based software pipeline. DISCUSSION Generators and generator comprehension are often regarded as superior to list comprehension due to the reduced footprint of in-flight data and the future potential of vertical parallelism via pipelining. List comprehensions, while having the drawback of requiring the presence of the entire working set in-flight, places no inherent restriction on the order of execution. This permits us to distribute the execution effort horizontally across
Re: Use of Python with GDAL. How to speed up ?
Julien Fiore wrote: > Thank you Serge for this generous reply, > > Vectorized code seems a great choice to compute the distance. If I > understand well, vectorized code can only work when you don't need to > access the values of the array, but only need to know the indices. You can access array elements in any order if you wrap your head around how indexing array with arrays works. Here is I'm transposing matrix on the fly > This > works well for the distance, but I need to access the array values in > the openness function. What really kills vectorization is conditional control flow constructions (if, break, continue). Some of them can be still be converted if you change algorithm. But some kill vectorization. For example first continue where you exclude edges is avoidable: you need to break you main loop in two, first loop will initialize edges, the second loop will work on the main image. But the second continue is a killer. Another example of algorightm change is small loops inside the main loop: E = 180.0 angle = numpy.min(90.0 - numpy.arctan((win[R+1:2*R][R]-win[R][R])/dist[R+1:2*R][R])) if angle > As regards array.array, it seems a bit complicated to reduce all my 2D > arrays to 1D arrays because I am working with the gdal library, which > works only with 'numeric' arrays. You can try to convert numeric array into array.array. Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
[EMAIL PROTECTED] wrote: > No. First of all, combining them with the & operator would be > the asnswer to having all four lamps lit in the same position. > But you want exactly 3 (in any combination). The correct way > to combine the switches (using my answer of a[7] b[2] c[5] d[3]) > is to use the boolean expression I gave you initially: Ah, that makes sense. I think I have a handle on it now. Of course, you did the grunt work of making the hex list, which might not have been so fun, but now I can work on using it to get the solution. Once I do, I'd love to compare my answer to yours, because something tells me yours will be much more elegant. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: New development windows, IronPython or PythonWin
Dan wrote: > > I realise its in beta. But long term, do you think that the win32com, > win32gui etc... will have no support because everyone jumps on the > Microsoft bandwagon? Aren't the windows support extensions supported > primarily by one guy, Mark Hammond? As a developer, this seams to leave > me with a vulnerability long term. Thanks for the advise. Bruno Desthuilliers wrote: > > Well, from what we've seen so far, I'd rather rely on open source > software than on proprietary one. An oss project lives as long as > someone is willing to maintain it, and anyone can pick it up. And I > wouldn't count on "every one jumping on MS wagon" neither. I find this comment curious, as IronPython *is* an open source software. Even if Microsoft is to stop its development today, anyone can pick up the source and continue. Seo Sanghyeon -- http://mail.python.org/mailman/listinfo/python-list
send email to string of emails
the code below outputs a string of emails (e.g. ['[EMAIL PROTECTED]', '[EMAIL PROTECTED]'] i would like to somehow send an email to everyone on the string of emails telling them 'thanks for emailing me' anyone know how to do this? much thanks ahead of time. from imaplib import * import getpass, re m = IMAP4("xx") m.login('x', 'xx') m.select('Inbox') status, data = m.search(None,'(SUBJECT "BIKES")') assert status=='OK', "Error. Message: %s"%data data = data[0] #you get your results in a list and search returns only one result assert data,"No results" #cool, we have results, but IMAP's search command only returns IDs so we have to fetch #msgs now status,senders = m.fetch(data.replace(' ',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])') assert status=='OK', "Error. Message: %s"%data ''.join([''.join(t) for t in senders]) senderlist =''.join([''.join(t) for t in senders]) emails = re.findall('([EMAIL PROTECTED])', senderlist) print emails -- http://mail.python.org/mailman/listinfo/python-list
Re: don't understand popen2
Sion Arrowsmith wrote: > Kent Johnson <[EMAIL PROTECTED]> wrote: > >>Sion Arrowsmith wrote: >> >>>(and please avoid the abuse of raw strings for Windows paths). >> >>Why do you consider that abuse of raw strings? > > I consider it abuse because it's not what they were invented for. > I consider discouraging it to be a good thing in order to reduce > the chances of people being bitten by, for instance: > os.listdir(r"C:\") > > File "", line 1 > os.listdir(r"C:\") > ^ > SyntaxError: EOL while scanning single-quoted string > > and getting all confused on this group. Judging from the traffic here, people are far more often bitten by *not* using raw strings for paths containing \ than they are by using them for paths ending with \. So perhaps we should encourage raw strings for Windows paths. ;) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are so many built-in types inheritable?
Fabiano Sidler wrote: > Hi folks! > > For debugging purposes I tried this: > > --- snip --- > def foo(): pass > function = type(foo) > > class PrintingFunction(function): > def __init__(self, func): > self.func = func > def __call__(self, *args, **kwargs): > print args, kwargs > return function.__call__(self, args, kwargs) > > class DebugMeta(type): > def __new__(self, name, bases, dict): > for name in dict: > if type(dict[name]) is function: > dict[name] = PrintingFunction(dict[name]) > > --- snap --- > > Now I tought I were able to let all maethod of classes with DebugMeta as > metaclass print out their arguments. But I got the following sad error: > > TypeError: Error when calling the metaclass bases > type 'function' is not an acceptable base type > > That's awful, isn't it? > What could I do to get the above code working? (No, I disliked to re- > implement without this unpleasant behaviour in Python.) You could do this with a simple decorator: http://wiki.python.org/moin/PythonDecoratorLibrary#head-d4ce77c6d6e75aad25baf982f6fec0ff4b3653f4 or I think your class PrintingFunction would work as class PrintingFunction(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print args, kwargs return self.func(*args, **kwargs) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding problems (é and è)
Martin v. Löwis wrote: > John Machin wrote: > >> and, for things like u'\u0565\u0582' (ARMENIAN SMALL LIGATURE ECH > >> YIWN), it does not even work. > > > > Sorry, I don't understand. > > 0565 is stand-alone ECH > > 0582 is stand-alone YIWN > > 0587 is the ligature. > > What doesn't work? At first guess, in the absence of an Armenian > > informant, for pre-matching normalisation, I'd replace 0587 by the two > > constituents -- just like 00DF would be expanded to "ss" (before > > upshifting and before not caring too much about differences caused by > > doubled letters). > > Looking at the UnicodeData helps here: > > 00DF;LATIN SMALL LETTER SHARP S;Ll;0;L;N;;German;;; > 0587;ARMENIAN SMALL LIGATURE ECH YIWN;Ll;0;L; 0565 0582N; > > So U+0587 is a compatibility character for U+0565,U+0582. Not sure > what the rationale for *this* compatibility character is, but in many > cases, they are in Unicode only for compatibility with some existing > encoding - if they had gone through the proper Unification, they should > not have been introduced as separate characters. The problem is that U+0587 is a ligature in Western Armenian dialect (hy locale) and a character in Eastern Armenian dialect (hy_AM locale). It is strange the code point is marked as compatibility char. It either mistake or political decision. It used to be a ligature before orthographic reform in 1930s by communist government in Armenia, then it became a character, but after end of Soviet Union (1991) they started to think about going back to old orthography. Though it hasn't happened and it's not clear if it will ever happen. So U+0587 is a character. By the way, this char/ligature is present on both Western and Eastern Armenian keyboard layouts: http://www.datacal.com/products/armenian-western-layout.htm It is between 9 and (. In Eastern Armenian this character is used in words և ( the word "and" in English) , արև ( "sun" in English) and hundreds others. Needless to say how many documents exist with this character. > > In many cases, ligature characters exist for typographical reasons; > other examples are > > FB00;LATIN SMALL LIGATURE FF;Ll;0;L; 0066 0066N; > FB01;LATIN SMALL LIGATURE FI;Ll;0;L; 0066 0069N; > FB02;LATIN SMALL LIGATURE FL;Ll;0;L; 0066 006CN; > FB03;LATIN SMALL LIGATURE FFI;Ll;0;L; 0066 0066 0069N; > FB04;LATIN SMALL LIGATURE FFL;Ll;0;L; 0066 0066 006CN; > > In these cases, it is the font designers which want to have code points > for these characters: the glyphs of the ligature cannot be automatically > derived from the glyphs of the individual characters. I can only guess > that the issue with that Armenian ligature is similar. > > Notice that the issue of U+00DF is entirely different: it is a character > on its own, not a ligature. That a common transliteration for this > character exists is again a different story. > > Now, as to what might not work: While compatibility decomposition > (NFKD) converts \u0587 to \u0565\u0582, the reverse process is not > supported. This is intentional, of course: there is no "canonical" > compatibility character for every decomposed code point. Seems like NFKD will damage Eastern Armenian text (there are millions of such documents). The result will be readable but the text will look strange to the person who wrote the text. Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove integer from float number
I think you ought to make your own class and define some of the special methods. mt -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > [EMAIL PROTECTED] wrote: > > >> (homework? a puzzle book?), I am just > >> wondering where the puzzle came from. > > > > The OP mentioned it came from a puzzle game That made me > > think there was likely at least one solution. > > Right, a computer puzzle game (a Myst-style game called Realms of > Illusion), and I know there's at least one answer because it's been > months since I finished the game. :) > > I also think, but can't say for sure, that there is just one solution. _I_ can say for sure, there is just one solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: Caching in memory for Apache
Simon Johnson wrote: > Dear All, > > I have decided to take the big plunge and drop the Microsoft platform > and use Mod_Python and Apache in it's place. > > I've never used Linux before this project so it's a really big learning > curve, but so far it's going well. I've managed to create some simple > pages using the basic of Python. > > One of the questions I have is: How do you cache stuff in memory? Say > I've got a bunch of stuff I need to create from a set of database rows. > Obviously, I do not want to consult the database each time I have a > request for my page. Is there anyway in Mod_python for me to store > values inside memory so I can look it up on the next GET request? It all depends a bit on what you want to cache and whether the data is specific to one users interaction with a page, or whether the data is able to be used across requests from multiple users. This will dictate whether you can use a global data cached within modules used to generate the page, whether you can use sessions, shared memory or whether you have no choice but to always go back to the database. As others have pointed out, don't get trapped in doing premature optimisation. More often than not what you may think will be a bottle neck will not and any problems if they even exist will be elsewhere. In respect of mod_python, it is also vitally important to understand the process/interpreter module under which Python runs within the context of Apache. A starting point for getting information about this is: http://www.dscpl.com.au/articles/modpython-004.html If you do decide that sessions may be useful to what you are doing, as pointed out by others, there can be limitations as to what data can be stored. For limitations in respect of sessions in mod_python have a look at: http://www.dscpl.com.au/articles/modpython-005.html Finally, make sure you use the latest version of mod_python available. Avoid using mod_python 2.7.X or 3.1.X as there are lots of known issues and problems. Not all problems are solved in 3.2.X version, but good progress has been made on getting rid of many issues. The main area which can still cause problems, especially when trying to cache data in the Apache process, is that of module loading and reloading. For a run down on issues in that area see: http://www.dscpl.com.au/articles/modpython-003.html A lot of work has already been done on solving these issues for 3.3.X version of mod_python. BTW, the best place to ask questions about mod_python is the mod_python mailing list. Thus, get yourself subscribed to it. Details of the mailing list are on the mod_python web site. Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > [EMAIL PROTECTED] wrote: > > > You have 4 panels, each with 20 lamps (label them 19 to 0): > > > > panel A > > panel B > > panel C > > panel D > > I'm sorry for being so dense, but I don't understand this. There are > four panels, yes. Each panel has eight switches, and each switch has 20 > lights. What do you mean when you say that each panel has 20 lamps? Oh, I see where the confusion is. EACH switch has 20 lamps. But, since ONLY 1 switch can be on, each panel shows exactly one pattern of lamps, correct? So we only consider panel A to have 20 lamps, the 20 that are selected by the switch. For the purposes of solving the puzzle, we simply want to know what the pattern is when switch 0 is selected, what the pattern is when switch 1 is selected, etc. for each of the four panels. > > > By the way, I have a program that solves the problem. > > You said you wanted to do it yourself, so if you need more > > help, I can walk you through how to solve it. > > I already know the solution (I had to cheat to get past this part of the > game, it was just too frustrating). I was always more interested in the > actual process of figuring it out via writing a program. You can tell me > your solution if you want and I can check it. I also posted it in the other reply, but here it is again: a[7] b[2] c[5] d[3] Remember, count from 0, switch 7 is the last switch. We can manually verify >>> print gmpy.digits(a[7],2) 111011000101 >>> print gmpy.digits(b[2],2) 110001110101 >>> print gmpy.digits(c[5],2) 101100111010 >>> print gmpy.digits(d[3],2) 0001011 111011000101 110001110101 101100111010 00001011 Note that in each column, there is exactly one 0, which means there is exaclty 3 1's in that column, therefore, a[7] b[2] c[5] d[3] is a solution. > This will at least confirm > that you understand the problem fully and that I'm just being moronic > when it comes to understanding your explanations. :) You're not moronic. I have 30 years experience with boolean algebra and digital logic. I understand what's trivial to me is not trivial to everyone. But I don't know how much you know and how much you want to work out yourself. You certainly CAN solve the problem by the tedious method you initially described. But since you specifically asked about use bitwise operators, I used that in my solution. I didn't want to spoil it for you, but say the word and I'll post my program code. -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python logo in high resolution format
On Fri, 2006-03-24 at 10:49 -0800, Robert Hicks wrote: > How about we all get tatoos? : ) ... still trying to scrape the old one off ... > > Robert > -- http://mail.python.org/mailman/listinfo/python-list
Re: Incremental Compression
On Sat, 2006-03-25 at 03:08 +0200, Eyal Lotem wrote: > Hey. > > I have a problem in some network code. I want to send my packets compressed, > but I don't want to compress each packet separately (via .encode('zlib') or > such) but rather I'd like to compress it with regard to the history of the > compression stream. If I use zlib.compressobj and flush it to get the > packet data, I cannot continue to compress with that stream. Yes, you can. Help on built-in function flush: flush(...) flush( [mode] ) -- Return a string containing any remaining compressed data. mode can be one of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH; the default value used when mode is not specified is Z_FINISH. If mode == Z_FINISH, the compressor object can no longer be used after calling the flush() method. Otherwise, more data can still be compressed. you want to call mycompressor.flush( zlib.Z_SYNC_FLUSH ) The difference between the flushes is this: 1. Z_SYNC_FLUSH. This basically send enough data so that the receiver will get everything you put in. This does decerase your compression ratio (however, in weird case when I last played with it, it helped.) 2. Z_FULL_FLUSH. This sends enough data so that the receiver will get everything you put in. This also wipes the compressors statistics, so the when you pick up where you left of, the compressor will compress about as well as if you had just started, you are wiping its memory of what it saw in the past. 3. Z_FINISH. This is the default action, this is what is killing you. Good luck - Adam DePrince > > I cannot wait until the end of the stream and then flush, because I need to > flush after every packet. > > Another capability I require is to be able to copy the compression stream. > i.e: To be able to create multiple continuations of the same compression > stream. Something like: > > a = compressobj() > pre_x = a.copy() > x = a.compress('my_packet1') > # send x > # x was not acked yet, so we must send another packet via the pre_x > compressor > y = pre_x.compress('my_packet2') > > Is there a compression object that can do all this? Ahh, you are trying to "pretune" the compressor before sending a little bit ... I think C-zlib does this, but I don't know for sure. - Adam DePrince -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > [EMAIL PROTECTED] wrote: > > > a = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] > > b = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] > > c = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] > > d = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] > > > Once you see that a[0],b[0],c[0],d[0] is not a solution, try a > > different set of switches. Repeat until you find a set that works. > > There is, in fact a solution, but I won't reveal it unless you ask. > > Using your hex list, I combined the four correct switches with the & > operator, and the result was 0. Shouldn't it be 1 for the correct answer? No. First of all, combining them with the & operator would be the asnswer to having all four lamps lit in the same position. But you want exactly 3 (in any combination). The correct way to combine the switches (using my answer of a[7] b[2] c[5] d[3]) is to use the boolean expression I gave you initially: >>> y = ((c[5] & d[3]) & (a[7] ^ b[2])) | ((a[7] & b[2]) & (c[5] ^ d[3])) >>> y 1048575 Note the answer is 2**20-1, not 1, the correct answer will have a 1 in EACH of the 20 bit positions (when y is printed in binary). Is 1048575 the right answer? >>> import gmpy >>> print gmpy.digits(y,2) Yes, it is the right answer. If you calculate y for EVERY possible permutation of switches a[0] b[0] c[0] d[0] a[0] b[0] c[0] d[1] a[0] b[0] c[0] d[2] a[0] b[0] c[0] d[3] a[0] b[0] c[0] d[4] a[0] b[0] c[0] d[5] a[0] b[0] c[0] d[6] a[0] b[0] c[0] d[7] a[0] b[0] c[1] d[0] . . . a[7] b[7] c[7] d[5] a[7] b[7] c[7] d[6] a[7] b[7] c[7] d[7] you'll find that a[7] b[2] c[5] d[3] is the ONLY solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie parsing question
[EMAIL PROTECTED] wrote: > Use Regular expressions > http://docs.python.org/lib/module-re.html > i tried to parse (below) with the regular expression: emails = re.findall('\S*\s([EMAIL PROTECTED])', senders) and got the following error: Traceback (most recent call last): File "/Life/School/Homework/Spring 2006/OPIM 399/Tutorial/IMAP/scannermailer.py", line 19, in -toplevel- emails = re.findall('\S*\s([EMAIL PROTECTED])', senders) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre.py", line 167, in findall return _compile(pattern, flags).findall(string) TypeError: expected string or buffer any help would be appreciated. [('460 (BODY[HEADER.FIELDS (FROM)] {46}', 'From: Kevin Feng <[EMAIL PROTECTED]>\r\n\r\n'), ')', ('461 (BODY[HEADER.FIELDS (FROM)] {37}', 'From: Kevin <[EMAIL PROTECTED]>\r\n\r\n'), ')'] -- http://mail.python.org/mailman/listinfo/python-list
Incremental Compression
Hey. I have a problem in some network code. I want to send my packets compressed, but I don't want to compress each packet separately (via .encode('zlib') or such) but rather I'd like to compress it with regard to the history of the compression stream. If I use zlib.compressobj and flush it to get the packet data, I cannot continue to compress with that stream. I cannot wait until the end of the stream and then flush, because I need to flush after every packet. Another capability I require is to be able to copy the compression stream. i.e: To be able to create multiple continuations of the same compression stream. Something like: a = compressobj() pre_x = a.copy() x = a.compress('my_packet1') # send x # x was not acked yet, so we must send another packet via the pre_x compressor y = pre_x.compress('my_packet2') Is there a compression object that can do all this? -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
[EMAIL PROTECTED] wrote: > a = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] > b = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] > c = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] > d = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] > Once you see that a[0],b[0],c[0],d[0] is not a solution, try a > different set of switches. Repeat until you find a set that works. > There is, in fact a solution, but I won't reveal it unless you ask. Using your hex list, I combined the four correct switches with the & operator, and the result was 0. Shouldn't it be 1 for the correct answer? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I handle #
Michael Sperlle wrote: > I need to write out a file containing the # comment. When I try to specify > it as part of a literal, everything afterward turns into a comment. > > I finally created a file containing the #, read it in, and used the > resulting variable as part of the string I created. > > But that is so kludgy, even a newbie like me is ashamed to use it, though > I did. > > Supposedly, I can us \x followed by the hex equivalent and somehow make > that work. > > Can anybody give an example of this; my attempts failed. Failed in what strange way? I don't see a problem at all: >>> open("bla.txt",'w').write("# some line with a hash comment\n") >>> open("bla.txt").read() '# some line with a hash comment\n' --Irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I handle #
Em Sáb, 2006-03-25 às 00:46 +, Michael Sperlle escreveu: > I need to write out a file containing the # comment. When I try to specify > it as part of a literal, everything afterward turns into a comment. $ python Python 2.3.5 (#2, Mar 6 2006, 10:12:24) [GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "hi # hi" hi # hi >>> print 'hi # hi' hi # hi >>> print r"hi # hi" hi # hi >>> print u"hi # hi" hi # hi What's up? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
How do I handle #
I need to write out a file containing the # comment. When I try to specify it as part of a literal, everything afterward turns into a comment. I finally created a file containing the #, read it in, and used the resulting variable as part of the string I created. But that is so kludgy, even a newbie like me is ashamed to use it, though I did. Supposedly, I can us \x followed by the hex equivalent and somehow make that work. Can anybody give an example of this; my attempts failed. Or is there something simpler? There must be. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie parsing question
Use Regular expressions http://docs.python.org/lib/module-re.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Caching in memory for Apache
On Fri, 2006-03-24 at 06:56 -0800, Simon Johnson wrote: > Dear All, > > I have decided to take the big plunge and drop the Microsoft platform > and use Mod_Python and Apache in it's place. > > I've never used Linux before this project so it's a really big learning > curve, but so far it's going well. I've managed to create some simple > pages using the basic of Python. > > One of the questions I have is: How do you cache stuff in memory? Say > I've got a bunch of stuff I need to create from a set of database rows. > Obviously, I do not want to consult the database each time I have a Why not hit the database each time? That's what it is there for. What you are trying to do is called premature optimization. You are facing a huge learning curve. My recommendation is to build it first with close adherence to the KISS principal. After its built, take it for a spin. If it is too slow, then tune it. Think towards implementation simplicity, not speed. You will probably find that whatever you build will be fast enough when you are finished. > request for my page. Is there anyway in Mod_python for me to store > values inside memory so I can look it up on the next GET request? Your database really is the best place for that. Good luck - Adam DePrince -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
[EMAIL PROTECTED] wrote: > You have 4 panels, each with 20 lamps (label them 19 to 0): > > panel A > panel B > panel C > panel D I'm sorry for being so dense, but I don't understand this. There are four panels, yes. Each panel has eight switches, and each switch has 20 lights. What do you mean when you say that each panel has 20 lamps? > By the way, I have a program that solves the problem. > You said you wanted to do it yourself, so if you need more > help, I can walk you through how to solve it. I already know the solution (I had to cheat to get past this part of the game, it was just too frustrating). I was always more interested in the actual process of figuring it out via writing a program. You can tell me your solution if you want and I can check it. This will at least confirm that you understand the problem fully and that I'm just being moronic when it comes to understanding your explanations. :) -- http://mail.python.org/mailman/listinfo/python-list
newbie parsing question
i have a list of that is: [('460 (BODY[HEADER.FIELDS (FROM)] {46}', 'From: Friend <[EMAIL PROTECTED]>\r\n\r\n'), ')', ('462 (BODY[HEADER.FIELDS (FROM)] {37}', 'From: Kun <[EMAIL PROTECTED]>\r\n\r\n'), ')'] how do i parse the email addresses out of it into another list or string? -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
[EMAIL PROTECTED] wrote: >> (homework? a puzzle book?), I am just >> wondering where the puzzle came from. > > The OP mentioned it came from a puzzle game That made me > think there was likely at least one solution. Right, a computer puzzle game (a Myst-style game called Realms of Illusion), and I know there's at least one answer because it's been months since I finished the game. :) I also think, but can't say for sure, that there is just one solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: C-API: A beginner's problem
Fabian Steiner wrote: > What do I have to change in order to make the code work? I'm afraid to say: your knowledge of C :-) But don't worry, C is an easy language to learn, and a very valuable skill to have. Baalbek -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
Michael Tobis wrote: > Yeah, I misread the question, but the gist of my query remains. > > > The odds are 100% if there is at least one solution. > > Let's not get too philosophical. My question was whether there was an a > priori reason for believing that there is a solution. > > > You want permutations with replacement, so there are 8**4 = 4096 > > Agreed. My mistake. > > >> These will turn on 15 lights in each set of 20, of which the number of > >> possibilities is C(15,20)**4 = 57779667567968256L > > > No, there are only 8 possible patterns on each panel. > > Not every possible 15 lamp pattern is realized > > Right, but that is exactly my point. This is the number of possible > selections of 15 out of 20 made four times. Any attempt will be a > member of that space. Then the probability of hitting a solution at > random is the ratio of solutions to that space. > > So I think my chance of success on a sinlge selection, assuming random > design of the switch banks, is correct: 1.9e-05 My error gave me the > wrong multiplier. It's 4096 rather than 1820. So now I'm goinq with a > 7.79% chance of randomly setting up the problem to yield a solution. Ok, random settings didn't make any sense since the problem was already set up. > > Still seems somwhat unlikely that there would be a solution unless the > problem were set up in advance. It would be easy to set up an answer. Then work backwards to create 7 bad settings for each switch, although I'm not sure how you would ensure not accidently creating another solution. Would be simple enough to verify, though. With only 4096 permutations, it only takes seconds to find the solution(s). > (homework? a puzzle book?), I am just > wondering where the puzzle came from. The OP mentioned it came from a puzzle game That made me think there was likely at least one solution. > > Was there more than one solution? No, there is exactly one solution where Y has 20 1's. Second best has only 16 1's, of which there are 8 solutions. For example: 16 110110110011 3 4 5 5 where the numbers are popcount, Y (in binary) and the four switch settings. > > mt -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are so many built-in types inheritable?
Hello? Or, is there any obvious reason for this behaviour I don't see? -- http://mail.python.org/mailman/listinfo/python-list
Re: imap folder scanner
Marco Carvalho wrote: > On 3/24/06, Sebastjan Trepca <[EMAIL PROTECTED]> wrote: > >> m.select('myfolder') > > Some attention is required here to retrieve subfolders. > Some imap servers like Cyrus and Courier uses "INBOX.subfolder" to > access subfolders. > -- > Marco Carvalho (macs) | marcoacarvalho(a)gmail.com > http://arrakis.no-ip.info | http://cdd.debian-br.org > Maceio - Alagoas - Brazil > Debian GNU/Linux unstable (Sid) > GNU-PG ID:08D82127 - Linux Registered User #141545 > Notícias Semanais do Debian em Português: http://www.debian.org/News/weekly > Alertas de Segurança Debian (DSA): http://www.debian.org/security so i have used the following code and have successfully saved a list of senders as a string. however, the string has much more information than just the email address and i am wondering what is the best way to parse the email address out of the entire string. sample string: >>> print status, senders OK [('460 (BODY[HEADER.FIELDS (FROM)] {46}', 'From: Friend <[EMAIL PROTECTED]>\r\n\r\n'), ')', ('462 (BODY[HEADER.FIELDS (FROM)] {37}', 'From: Kun <[EMAIL PROTECTED]>\r\n\r\n'), ')'] how do i just get the two email addresses out of there? my code is: from imaplib import * import getpass m = IMAP4("") m.login('xx', 'xxx') m.select('Inbox') status, data = m.search(None,'(SUBJECT "BIKES")') assert status=='OK', "Error. Message: %s"%data data = data[0] #you get your results in a list and search returns only one result assert data,"No results" #cool, we have results, but IMAP's search command only returns IDs so we have to fetch #msgs now status,senders = m.fetch(data.replace(' ',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])') assert status=='OK', "Error. Message: %s"%data print senders -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
Yeah, I misread the question, but the gist of my query remains. > The odds are 100% if there is at least one solution. Let's not get too philosophical. My question was whether there was an a priori reason for believing that there is a solution. > You want permutations with replacement, so there are 8**4 = 4096 Agreed. My mistake. >> These will turn on 15 lights in each set of 20, of which the number of >> possibilities is C(15,20)**4 = 57779667567968256L > No, there are only 8 possible patterns on each panel. > Not every possible 15 lamp pattern is realized Right, but that is exactly my point. This is the number of possible selections of 15 out of 20 made four times. Any attempt will be a member of that space. Then the probability of hitting a solution at random is the ratio of solutions to that space. So I think my chance of success on a sinlge selection, assuming random design of the switch banks, is correct: 1.9e-05 My error gave me the wrong multiplier. It's 4096 rather than 1820. So now I'm goinq with a 7.79% chance of randomly setting up the problem to yield a solution. Still seems somwhat unlikely that there would be a solution unless the problem were set up in advance. (homework? a puzzle book?), I am just wondering where the puzzle came from. Was there more than one solution? mt -- http://mail.python.org/mailman/listinfo/python-list
Re: imap folder scanner
On 3/24/06, Sebastjan Trepca <[EMAIL PROTECTED]> wrote: > m.select('myfolder') Some attention is required here to retrieve subfolders. Some imap servers like Cyrus and Courier uses "INBOX.subfolder" to access subfolders. -- Marco Carvalho (macs) | marcoacarvalho(a)gmail.com http://arrakis.no-ip.info | http://cdd.debian-br.org Maceio - Alagoas - Brazil Debian GNU/Linux unstable (Sid) GNU-PG ID:08D82127 - Linux Registered User #141545 Notícias Semanais do Debian em Português: http://www.debian.org/News/weekly Alertas de Segurança Debian (DSA): http://www.debian.org/security -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding problems (é and è)
John Machin wrote: >> and, for things like u'\u0565\u0582' (ARMENIAN SMALL LIGATURE ECH >> YIWN), it does not even work. > > Sorry, I don't understand. > 0565 is stand-alone ECH > 0582 is stand-alone YIWN > 0587 is the ligature. > What doesn't work? At first guess, in the absence of an Armenian > informant, for pre-matching normalisation, I'd replace 0587 by the two > constituents -- just like 00DF would be expanded to "ss" (before > upshifting and before not caring too much about differences caused by > doubled letters). Looking at the UnicodeData helps here: 00DF;LATIN SMALL LETTER SHARP S;Ll;0;L;N;;German;;; 0587;ARMENIAN SMALL LIGATURE ECH YIWN;Ll;0;L; 0565 0582N; So U+0587 is a compatibility character for U+0565,U+0582. Not sure what the rationale for *this* compatibility character is, but in many cases, they are in Unicode only for compatibility with some existing encoding - if they had gone through the proper Unification, they should not have been introduced as separate characters. In many cases, ligature characters exist for typographical reasons; other examples are FB00;LATIN SMALL LIGATURE FF;Ll;0;L; 0066 0066N; FB01;LATIN SMALL LIGATURE FI;Ll;0;L; 0066 0069N; FB02;LATIN SMALL LIGATURE FL;Ll;0;L; 0066 006CN; FB03;LATIN SMALL LIGATURE FFI;Ll;0;L; 0066 0066 0069N; FB04;LATIN SMALL LIGATURE FFL;Ll;0;L; 0066 0066 006CN; In these cases, it is the font designers which want to have code points for these characters: the glyphs of the ligature cannot be automatically derived from the glyphs of the individual characters. I can only guess that the issue with that Armenian ligature is similar. Notice that the issue of U+00DF is entirely different: it is a character on its own, not a ligature. That a common transliteration for this character exists is again a different story. Now, as to what might not work: While compatibility decomposition (NFKD) converts \u0587 to \u0565\u0582, the reverse process is not supported. This is intentional, of course: there is no "canonical" compatibility character for every decomposed code point. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: imap folder scanner
Sebastjan Trepca wrote: > A very simple example... > > import imaplib > m = imap.IMAP4() > m.login(username,password) > m.select('myfolder') > status, data = m.search(None,'(SUBJECT "BIKES")') > assert status=='OK', "Error. Message: %s"%data > data = data[0] #you get your results in a list and search returns only > one result > assert data,"No results" > #cool, we have results, but IMAP's search command only returns IDs so > we have to fetch > #msgs now > status,senders = m.fetch(data.replace(' > ',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])') > assert status=='OK', "Error. Message: %s"%data > > Now you just have to parse the "senders" data. There are many examples > about sending emails with python, like this one: > > def send_notice(): > import smtplib > msg = 'we got your mail, indeed' > from email.MIMEText import MIMEText > mail = MIMEText(msg, 'plain', 'utf-8') > mail['From'] =fro='[EMAIL PROTECTED]' > mail['Subject'] = "Spam machine" > mail['To'] = to = '[EMAIL PROTECTED]' > server = smtplib.SMTP('localhost') > errors = server.sendmail(fro, to, mail.as_string()) > server.quit() > > That other program should be very simple to make now. > > Sebastjan > > On 3/24/06, Kun <[EMAIL PROTECTED]> wrote: >> Hey guys, I would like to have a code in python (as simple as possible) >> to scan a specific folder in my mailbox and if the subject is equal to, >> say, 'BIKES', I would like to have the code automatically send the >> SENDER an email saying something like "We have received your Email". >> Furthermore, I would also like to somehow save the sender's email into a >> list which would be compiled by another python program into an html file >> that would show a list of email addresses whose subject matched 'BIKE' >> >> I know i am asking for a lot but since i am new to python, can someone >> help me out with this? Whether its tips or code, i'll be very excited to >> hear your answer. Thanks. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> Thank you very much for your help. I am trying to use your code and currently it works up to the 'fetch', where I am getting the following error: error: FETCH command error: BAD ['Protocol Error: "Specified message set is invalid".'] I guess I do not understand why you have data.replace('',',') and what ",',' means. Thanks so much. Kun -- http://mail.python.org/mailman/listinfo/python-list
Re: Python types
Salvatore a écrit : > Hello, > > I've read several articles where it's said that Python is weakly typed. > I'm a little surprised. All objects seem to have a perfectly defined > type > Am i wrong? Depends on your definition of 'type'. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
Caleb Hattingh wrote: > I agree that integer division should return an integer, because > using the operator at all means you expect one. so what is x / y ? an integer division ? something else ? -- http://mail.python.org/mailman/listinfo/python-list
Please help me to resolve this issue
Hello everyone, I am pretty new in python. Please give me any idea about this issue: There is a function like this in my c dll: typedef void (WINAPI *myCallBack) (unsigned int myarg1, unsigned int myarg2) bool myfunc(myCallBack mycall) In my python code, I was able to access other functions in the dll, but I have no idea how to call myfunc() because of WINAPI argument. Thanks in advance. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
Hi Christoph On my linux py-2.4.1: >>> 4.0//2 # Integer division, but still returns a float. 2.0 >>> 4.0//2 == 2 True >>> 4.0//2 doesn't return an integer, but the equality against an integer still holds. I agree that integer division should return an integer, because using the operator at all means you expect one.Having to cast it after integer division seems unnecessary. Unfortunately, I have zero say on the matter :) This issue was probably discussed at length when the integer division operator (//) was introduced. It is possible there is a good reason behind this, but I don't know it. regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Python types
Salvatore wrote: > Hello, > > I've read several articles where it's said that Python is weakly typed. > I'm a little surprised. All objects seem to have a perfectly defined > type > > Am i wrong? No, you're right. It seems like a lot of people conflate weak vs. strong typing and static vs. dynamic typing. Back when I was in CS classes in the early 1990s, the distinction was pretty universal, but in recent years it seems like more people are wrongly assuming that strong typing and static typing go hand in hand. C, C++: Weakly, statically typed Java, ML: Strongly, statically typed. VB, tcl (kind of): Weakly, dynamically typed Smalltalk, Python: Strongly, dynamically typed Note that both axes are continuums. C++ is mostly statically typed, but it's got rtti and other runtime typing facilities. Java is pretty strongly typed, but not to the degree that ML is. -- http://mail.python.org/mailman/listinfo/python-list
Python C wrapper question
Hello, Gurus, I have a question on wrapping C function in Python. My C code is like this: typedef void (WINAPI *myCallBack) (unsigned int myarg1, unsigned int myarg2) bool myfunc(myCallBack callfunc) Now I want to call myfunc in Python, what should I do? Thanks, Stone -- http://mail.python.org/mailman/listinfo/python-list
Re: Python types
Salvatore wrote: > I've read several articles where it's said that Python is weakly typed. > I'm a little surprised. All objects seem to have a perfectly defined > type Hoping to head off another debate: http://wiki.python.org/moin/StrongVsWeakTyping STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
[EMAIL PROTECTED] wrote: > John Salerno wrote: > > John Salerno wrote: > > > > > Anyway, any advice for how to proceed would be great! I hope I described > > > it well enough. > > > > Ok, after reading the suggestions, I feel better about proceeding. But > > one question: how exactly do I come up with 32 different 20-bit integers > > for each switch? > > Eight numbers for each switch, 32 total. Should be: Eight numbers for each panel, 32 total. > > Make a list for each panel and in each list, put in eight binary > numbers using the position in the list to represent the switch number. > So we'll want to label our switches 0-7. > > > Do I need to figure out the bits for each one manually? > > Yes, you get them from your diagram showing which lamps are > lit for each switch. > > > And how is this written in Python? Using hex? > > That's one way to do it. I did it that way because I have the > hex patterns memorized. > > I have already gone to the trouble of converting all your patterns to > hex numbers, if you're interested. If you want to do it yourself, > simply ignore this. > > a = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] > b = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] > c = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] > d = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] > > Now since the panels are now lists, we use an index representing > the switch to retrieve the lamps lit by that switch. > > Refering to my original boolean equation, replace A1 by a[0], > B1 by b[0], etc. to evaluate that set of switches. > > Once you see that a[0],b[0],c[0],d[0] is not a solution, try a > different set of switches. Repeat until you find a set that works. > There is, in fact a solution, but I won't reveal it unless you ask. > > If you need help in figuring out how to walk through all 4096 possible > switch sets, just ask. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python types
"Salvatore" <[EMAIL PROTECTED]> writes: > I've read several articles where it's said that Python is weakly > typed. I'm a little surprised. All objects seem to have a perfectly > defined type > > Am i wrong? You're right. All Python values are strongly typed; they don't, in general, change their type; and operations between values of mismatched types are not allowed. A more recent distinction than "strong" vs "weak" typing, is "dynamic" vs "static" typing. "Typing: Strong vs. Weak, Static vs. Dynamic" http://www.artima.com/weblogs/viewpost.jsp?thread=7590> -- \ "I would rather be exposed to the inconveniences attending too | `\ much liberty than those attending too small a degree of it." | _o__) -- Thomas Jefferson | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Strings and % sign fails - Help Please
Siah wrote: > Problem Solved. The problem was with psycopg.Binary whose mere job is > to convert bytes into clear text for sql statement. no, its job is to wrap strings that contain binary blobs, so that data binding works properly. you're supposed to do cursor.execute(statement, Binary(data)) and not cursor.execute(Binary(statement)) or cursor.execute("some statement %s" % Binary(statement)) or some other sillyness. it's an object wrapper, not an escape function for arbitrary SQL. Python's not PHP. for more details, see "Type Objects and Constructors" on this page http://www.python.org/dev/peps/pep-0249/ -- http://mail.python.org/mailman/listinfo/python-list
Re: New development windows, IronPython or PythonWin
Hi Dan Pythonwin just adds support for specifically MS Windows features, most prominently COM; writing Excel scripts in python is so cool. The standard python distribution for windows runs perfectly on windows. I'm not sure whether this was clear to you or not. Also, Thomas ctypes and comtypes (by Thomas(?) Heller) also allow COM integration, though I don't think it is as complete as the pythonwin support. Also, I think IronPython is also supported by only one guy - Jim Hugunin. The fact that IronPython development is effectively being sponsored by Microsoft doesn't fill me with great expectations either, although it would be a good thing if they really supported it well. rgds Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: COM Client / Server creation?
[EMAIL PROTECTED] (John J. Lee) writes: [...] > Not covered in the book, and particularly useful for implementing > native clients and servers is ctypes / comtypes (but still not stable; > also, I've only personally used it for writing a client, and a very > simple one at that): > > http://starship.python.net/crew/theller/ctypes/com.html Just to clarify this: ctypes IS stable, and in fact will be part of Python 2.5 (first alpha to be released in a week or so). comtypes is the "work-in-progress" (though it has been quite useable, at least for the simple stuff I did, for some time now). It's all quite elegant, too. John -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
Michael Tobis wrote: > First do a little estimation. We know we have to find four out of 16 > switches, 4 panels, eight switches each, 32 total. > so the number of possibilities to search is only C(4,16) = > 1820, so an exhaustive search will work. Yes, but for the wrong reason. It's not combinations, the switch selection A = 1 B = 2 C = 3 D = 4 is not the same as A = 4 B = 3 C = 2 D = 1 You want permutations with replacement, so there are 8**4 = 4096 possibilities, which is still tractable. > > These will turn on 15 lights in each set of 20, of which the number of > possibilities is C(15,20)**4 = 57779667567968256L No, there are only 8 possible patterns on each panel. Not every possible 15 lamp pattern is realized. > > The number of these that are successes is the number of ways to pick 3 > out of 4 twenty times: 4**20 = 1099511627776L > > For each pick, your chance of success is then > float(1099511627776L)/57779667567968256L = 1.9029386530869287e-05 Chance doesn't enter into it. Unless you ask what is the chance that a randomly selected switch pattern is a solution? But no one is asking that. > > You get 1820 distinct tries. Assuming no overlap (which slightly > overestimates your chances if it's a false assumption), the odds that > there is a solution are > > 1820 * 1.9029386530869287e-05 = 0.034633483486182101 > > or about 3.5%. Not great. The odds are 100% if there is at least one solution. > > There seem to be some symmetries I haven't used, which may conceivably > help your cause. I just wonder if you have some basis for beleiving > that there is a solution. There is. I solved it using the technique I outlined in my previous posts. > > mt -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance profiling Python code
Em Sex, 2006-03-24 às 15:58 -0500, Jack Diederich escreveu: > As a last resort you can write the sensitive bits in C and add a python > wrapper. For the ICFP contest[1] each year I write the few primitives > in C and all the logic in python and it works quite well. Before that, try Psyco. It helps a lot sometimes. HTH, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Looking for a Python wrapper for Nvidia Cg
Hello all, I am working on some games and some Nvidia Cg graphics. I am looking for python that provides wrappers over the Nvidia Cg API. Does anyone know where I may find what I am looking for? AIM -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > John Salerno wrote: > > > Anyway, any advice for how to proceed would be great! I hope I described > > it well enough. > > Ok, after reading the suggestions, I feel better about proceeding. But > one question: how exactly do I come up with 32 different 20-bit integers > for each switch? Eight numbers for each switch, 32 total. Make a list for each panel and in each list, put in eight binary numbers using the position in the list to represent the switch number. So we'll want to label our switches 0-7. > Do I need to figure out the bits for each one manually? Yes, you get them from your diagram showing which lamps are lit for each switch. > And how is this written in Python? Using hex? That's one way to do it. I did it that way because I have the hex patterns memorized. I have already gone to the trouble of converting all your patterns to hex numbers, if you're interested. If you want to do it yourself, simply ignore this. a = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] b = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] c = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] d = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] Now since the panels are now lists, we use an index representing the switch to retrieve the lamps lit by that switch. Refering to my original boolean equation, replace A1 by a[0], B1 by b[0], etc. to evaluate that set of switches. Once you see that a[0],b[0],c[0],d[0] is not a solution, try a different set of switches. Repeat until you find a set that works. There is, in fact a solution, but I won't reveal it unless you ask. If you need help in figuring out how to walk through all 4096 possible switch sets, just ask. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strings and % sign fails - Help Please
Problem Solved. The problem was with psycopg.Binary whose mere job is to convert bytes into clear text for sql statement. I'll be filing a bug. Thanks everyone, Sia -- http://mail.python.org/mailman/listinfo/python-list
Re: How to test wxPython by unittest
sillyemperor: > I was a new guy of Python,when i want to test my wxPython app by > unittest,it couldn`t work.I fund a stubmaker.py but it only for > wxDialog but all widgets.Can someone can tell me how test wxPython by > unittest?Thanks > Here's a small example to get you started: import unittest, wx class TextCtrlTest(unittest.TestCase): def setUp(self): app = wx.App(0) frame = wx.Frame(None) self.textCtrl = wx.TextCtrl(frame) def testInitialContents(self): self.assertEqual('', self.textCtrl.GetValue()) def testAppendText(self): self.textCtrl.AppendText('whatever') self.assertEqual('whatever', self.textCtrl.GetValue()) def testAppendTextTwice(self): self.textCtrl.AppendText('whatever') self.textCtrl.AppendText('and then some') self.assertEqual('whateverand then some', self.textCtrl.GetValue()) if __name__ == '__main__': unittest.main() Cheers, Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: converting to a binary number?
[EMAIL PROTECTED] wrote: > John Salerno wrote: >> I'm having some trouble finding a function that converts numbers >> (whether integer, hex, whatever) to its binary representation. Is there one? >> >> Thanks. > > Get the Gnu Multiple Precision library for Python module (Google GMPY). Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Linear regression in NumPy
> The version I have in front of me is a bit shorter, 252 pages, but describes > polyfit in section 5.3 on page 91 along with the other polynomial functions. > lstsq (linear_least_squares is a backwards-compatibility alias that was > recently > moved to numpy.linalg.old) is described in section 10.1 on page 149. Oops, sorry, shouldn't have posted before reading the whole document... You are right, of course, both functions are explained. I wonder why the acrobat's search function doesn't work, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
Just because nobody has mentioned them so far: - SciTe is a perfect editor for Pyhton on Win and Linx - PyScripter is a wonderful IDE (but only on Win) - DrPython is a nice platform independent editor/mini-IDE There is no one editor that could be called the best one, but there are many which are far better suited for Python than the simple standard text editors (Notepad & Co). Maybe you prefer to have one editor that suits all your programming and typing needs (not only Python), so you don't have to use different editors Python, HTML, XML, config files etc. SciTe performs very well here, and of course also Emacs... -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > [EMAIL PROTECTED] wrote: > > > Then you'll want to represent the lights as a 20-bit binary number. > > > > Each bit position corresponds to 4 lamps > > I'm not sure I understand that. If I use a 20-bit number, wouldn't each > bit correspond to a single light on each switch? What do you mean that > each bit is 4 lamps? You have 4 panels, each with 20 lamps (label them 19 to 0): panel A panel B panel C panel D ^ ^ | | lamp 19lamp 0 There are 4 lamps labeled 19, 4 labeled 18, etc. The boolean equation I gave you is the solution to a single lamp position. If a 0 represents OFF and a 1 represents ON, then this is equivalent to 4 20-bit binary numbers and you can use bitwise operators to solve all 20 lamp positions simultaneously. For each bit position, the boolean equation returns a 1 in the repective bit if there are exactly 3 1's in that lamp position of the 4 panels. The first switch in each panel lights the lamps: A 010111011100 B 1101110110110101 C 00110001 D 0111011011011011 You can, by hand, figure out which bit positions have exactly 3 1's vertically. A 010111011100 B 1101110110110101 C 00110001 D 0111011011011011 -- Y 10100100110111000101 So, as you already know, setting switch 1 on each panel is not a solution, we need a 1 in each bit position. You can determine this from the decimal representation. A 20-bit binary number of all 1's would be 2**20 - 1, so if Y = 1048575, then Y is a solution. In my example, I used hex to enter the sample values just because it was easier: Group the 20 bits into five groups of 4, and convert each group to a hex character A 0101 1101 1100 f5fdc Repeating the example (correcting the typo in the first post) >>> A1 = 0xf5fdc >>> B1 = 0xddb7d >>> C1 = 0xf37bd >>> D1 = 0x77edb >>> Y = ((C1 & D1) & (A1 ^ B1)) | ((A1 & B1) & (C1 ^ D1)) >>> Y 675269 We can see this is not a solution. Converting Y to binary allows us to see which lamp positions have three lit and confirm that the boolean equation matches our hand calculation. >>> print gmpy.digits(Y,2) 10100100110111000101 By the way, I have a program that solves the problem. You said you wanted to do it yourself, so if you need more help, I can walk you through how to solve it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
Andrew Koenig wrote: > Christoph Zwerschke wrote: > >> Anyway this would be an argument only against the variant of typecasting a >> float with a fractional part. But what about the other variant which >> raises an error if there is a fractional part, but works if the float is >> actually an exact integer, like the result of 4.0//2. > > I think that's a really bad idea, because of the possibility that the result > might happen to be an exact integer on one implementation but not another. > In such situations, the fact that it might fail on implementation X may well > be impossible to detect by any amount of testing on implementation Y. Such > untestable errors are such a nuisance that it would better for the language > to encourage programmers to give them a wide berth. 1./20*40 == 2 or math.sqrt(4.0) == 2 may not always be True (on my platform it is True), but on every platform 4.0//2 == 2 should be True. More general, the result of a//b should always be an exact integer, and a//b == int(a/b) for all positive numbers a,b, no matter on which platform. If not, I would consider a//b broken on that platform. And if a//b == int(a/b) is True, I think it is also reasonable to expect that a//b * list is the same as int(a/b) * list -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to learn perl for a python programmer?
Tell 'them' you need a uniform installation of your scipting language across all servers to ensure correct operation of your script then ensure its python that gets loaded ;-) I took a course in perl from Well House Consultants in the UK, which was good; then had an immediate use for perl, which helped me remember. I used the Well House manual and the Camel book for reference. (http://www.wellho.net/ - Tell Graham Paddy sent you). P.S. I don't have any connection to Well House, apart from learning Perl through them. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: converting to a binary number?
John Salerno wrote: > I'm having some trouble finding a function that converts numbers > (whether integer, hex, whatever) to its binary representation. Is there one? You might like this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
PythonStudent wrote: > Hi, > Can one of you say to me what's the best editor for editing the python > programs ( for linux or windows ) What may be "best" for me, may not necessarily work for you nor anybody else. Personally, I like to use Kate, Pico, or Joe on Linux, and Notepad2 or IDLE editor for Windows. Cheers, -M -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance profiling Python code
On Fri, Mar 24, 2006 at 09:33:55PM +0100, Andreas R?sdal wrote: > Hi, > > I'm using the Python profiler to optimize a pathfinding algorithm of a > game, and would like some help from someone who knows how to improve the > performance of Python code. The algorithm is A-Star, and it works > correctly. However, the interface that I made between the A-Star > pathfinding algorithm and the map data structure is what I've found to be > a bottle-neck so far. > > So are you able to spot any solutions to improving the performance of the > methods which I've indentified as bottlenecks here? > You have methods for accessing members, just access the members directly. Differently worded: don't write try to write Java/C++ in python! This will save you lots of function call overhead. For the adjacent tiles you could compute the list once and store it in the tiles (assuming the tiles don't move around). As a last resort you can write the sensitive bits in C and add a python wrapper. For the ICFP contest[1] each year I write the few primitives in C and all the logic in python and it works quite well. -Jack [1] http://icfpcontest.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Creating condensed expressions
[EMAIL PROTECTED] wrote: > Nevermind, I didn't understand the problem/question... Sorry. > > Bye, > bearophile > Really? Your solution looks fine to me. In any case, here's an alternative approach to the (based on the same understanding of the problem as bearophile's, but with the additional requirement that the input terms be sorted) >>> from itertools import groupby >>> from operator import itemgetter >>> src_iter = ((i[:-1],i[-1]) for i in src.splitlines()) #src must be sorted >>> grouped = groupby(src_iter, itemgetter(0)) >>> stemmed = ((stem, "".join(i[1] for i in values)) for stem, values in >>> grouped) >>> [(len(s[1])>1 and "%s[%s]" or "%s%s") % s for s in stemmed] ['apple[12]', 'apple3_SD', 'form[ABC]', 'kla_M[MB]', 'kca_MM'] >>> Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
First do a little estimation. We know we have to find four out of 16 switches, so the number of possibilities to search is only C(4,16) = 1820, so an exhaustive search will work. These will turn on 15 lights in each set of 20, of which the number of possibilities is C(15,20)**4 = 57779667567968256L The number of these that are successes is the number of ways to pick 3 out of 4 twenty times: 4**20 = 1099511627776L For each pick, your chance of success is then float(1099511627776L)/57779667567968256L = 1.9029386530869287e-05 You get 1820 distinct tries. Assuming no overlap (which slightly overestimates your chances if it's a false assumption), the odds that there is a solution are 1820 * 1.9029386530869287e-05 = 0.034633483486182101 or about 3.5%. Not great. There seem to be some symmetries I haven't used, which may conceivably help your cause. I just wonder if you have some basis for beleiving that there is a solution. mt -- http://mail.python.org/mailman/listinfo/python-list
Re: Python types
Steve M schrieb: > I think it means that names, not objects, are weakly typed. So you can > have: > a = 4 > a = 'hello' > > and there is no problem. The name 'a' doesn't have any type associated > with it. This contrasts with strongly typed language like C where you > declare the type of the name (variable) and the compiler objects at > compile time if you attempt to assign a value of a different type. void foo() { int *c = "hello weakly typed C!"; } 192:/tmp deets$ gcc -c test.c test.c: In function `foo': test.c:5: warning: initialization from incompatible pointer type So I wouldn't call C strongly typed The distinction is usually made on two axis: strong-weak and static-dynamic. Python is a strong-typed, dynamic language. JAVA is strong-typed static. And PHP is weakly-typed dynamic. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Performance profiling Python code
Hi, I'm using the Python profiler to optimize a pathfinding algorithm of a game, and would like some help from someone who knows how to improve the performance of Python code. The algorithm is A-Star, and it works correctly. However, the interface that I made between the A-Star pathfinding algorithm and the map data structure is what I've found to be a bottle-neck so far. As a start, I'd like to optimize the methods with the highest cumulative time spent using CPU, which are the ones on the top of the profiling out-put attached below (get_tile_adjacent etc.) So are you able to spot any solutions to improving the performance of the methods which I've indentified as bottlenecks here? Thanks in advance! Andreas R. The source code of the main faile is here: http://svn.gna.org/viewcvs/openrts/trunk/openrts/common/map.py?rev=89&view=markup Profiling output is here: ncalls tottime percall cumtime percall filename:lineno(function) /home/andreas/openrts/openrts/openrts/common/map.py:190(get_tile_adjacent) 1620020.6800.0000.6800.000 /home/andreas/openrts/openrts/openrts/common/map.py:56(get_tile) 1296000.5700.0000.5700.000 /home/andreas/openrts/openrts/openrts/common/map.py:217(wrap_map_pos) 1298370.4800.0000.4800.000 :0(append) 81000.1900.0000.4300.000 /home/andreas/openrts/openrts/openrts/common/map.py:253(get_tile_height_pos) 81000.0800.0000.2700.000 /usr/lib/python2.4/random.py:213(randint) 81000.1600.0000.1900.000 /usr/lib/python2.4/random.py:149(randrange) 10.0000.0000.1700.170 /home/andreas/openrts/openrts/openrts/common/map.py:26(__init__) 10.0700.0700.1700.170 /home/andreas/openrts/openrts/openrts/common/map.py:32(init_map) 81000.0800.0000.1100.000 /home/andreas/openrts/openrts/openrts/common/map.py:234(get_tile_height) -- http://mail.python.org/mailman/listinfo/python-list
Re: converting to a binary number?
that's great! I will try! :-)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Creating condensed expressions
David Hirschfield <[EMAIL PROTECTED]> writes: >Here's the problem: Given a list of item names like: >apple1 >apple2 >apple3_SD >formA >formB >formC >kla_MM >kla_MB >kca_MM >which is a subset of a much larger list of items, >is there an efficient algorithm to create condensed forms that match >those items, and only those items? Such as: >apple[12] >apple3_SD >form[ABC] >kla_M[MB] >kca_MM >The condensed expression syntax only has [...] and * as operators. [...] >matches a set of individual characters, * matches any string. >I'd be satisfied with a solution that only uses the [...] syntax, since >I don't think it's possible to use * without potentially matching items >not explicitly in the given list. >I'm not sure what this condensed expression syntax is called (looks a >bit like shell name expansion syntax), and I'm not even sure there is an >efficient way to do what I'm asking. Any ideas would be appreciated. If you used regular expressions instead of globs then I think what you want is to optimize the regular expression for: 'apple1|apple2|apple3_SD|formA|formB|formC|kla_MM|kla_MB|kca_MM' then spit the optimised finite automaton back out. Of course if you're just searching Python might do a decent job of optimising it anyway. Looking at: http://en.wikipedia.org/wiki/Finite_state_machine#Optimization they make it sound so easy!. There's also a whole bunch of tools on that page. Maybe there's an optimiser you can use in one of them. Failing that I guess you build a tree and try to merge nodes where they fork. I suspect an optimal solution would be hard but if you knew your input did have lots of redundancy a simple algorithm might work. Or I could be talking crap as usual. Eddie -- http://mail.python.org/mailman/listinfo/python-list
Re: converting to a binary number?
John Salerno wrote: > I'm having some trouble finding a function that converts numbers > (whether integer, hex, whatever) to its binary representation. Is there one? > > Thanks. Get the Gnu Multiple Precision library for Python module (Google GMPY). >>> import gmpy >>> help(gmpy.digits) Help on built-in function digits: digits(...) digits(x[,base]): returns Python string representing x in the given base (2 to 36, default 10 if omitted or 0); leading '-' present if x<0, but no leading '+' if x>=0. x must be an mpz, or else gets coerced into one. >>> for i in range(16): print gmpy.digits(i,2) 0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python types
I think it means that names, not objects, are weakly typed. So you can have: a = 4 a = 'hello' and there is no problem. The name 'a' doesn't have any type associated with it. This contrasts with strongly typed language like C where you declare the type of the name (variable) and the compiler objects at compile time if you attempt to assign a value of a different type. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Creating condensed expressions
[EMAIL PROTECTED] a écrit : > Nevermind, I didn't understand the problem/question... Sorry. actually, I think *you* got it right. -- http://mail.python.org/mailman/listinfo/python-list
Python types
Hello, I've read several articles where it's said that Python is weakly typed. I'm a little surprised. All objects seem to have a perfectly defined type Am i wrong? Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
John Salerno wrote: > Anyway, any advice for how to proceed would be great! I hope I described > it well enough. Ok, after reading the suggestions, I feel better about proceeding. But one question: how exactly do I come up with 32 different 20-bit integers for each switch? Do I need to figure out the bits for each one manually? And how is this written in Python? Using hex? -- http://mail.python.org/mailman/listinfo/python-list
Re: overlapping sets
There is a sets.Set class built in to Python. You might want to use this instead of lists. It defines some handy set operations like intersection, union, and so on. from sets import Set my_sets = { 'one' : Set([0,4,7,9]), 'two' : Set([0,3,7,9]), etc... } -- http://mail.python.org/mailman/listinfo/python-list
Re: a problem to solve
[EMAIL PROTECTED] wrote: > Then you'll want to represent the lights as a 20-bit binary number. > > Each bit position corresponds to 4 lamps I'm not sure I understand that. If I use a 20-bit number, wouldn't each bit correspond to a single light on each switch? What do you mean that each bit is 4 lamps? -- http://mail.python.org/mailman/listinfo/python-list
converting to a binary number?
I'm having some trouble finding a function that converts numbers (whether integer, hex, whatever) to its binary representation. Is there one? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding problems (� and
John Machin wrote: > Some of the transformations are a little unfortunate :-( here's a slightly silly way to map a unicode string to its "unaccented" version: ### import unicodedata, sys CHAR_REPLACEMENT = { 0xc6: u"AE", # LATIN CAPITAL LETTER AE 0xd0: u"D", # LATIN CAPITAL LETTER ETH 0xd8: u"OE", # LATIN CAPITAL LETTER O WITH STROKE 0xde: u"Th", # LATIN CAPITAL LETTER THORN 0xdf: u"ss", # LATIN SMALL LETTER SHARP S 0xe6: u"ae", # LATIN SMALL LETTER AE 0xf0: u"d", # LATIN SMALL LETTER ETH 0xf8: u"oe", # LATIN SMALL LETTER O WITH STROKE 0xfe: u"th", # LATIN SMALL LETTER THORN } class unaccented_map(dict): def mapchar(self, key): ch = self.get(key) if ch is not None: return ch ch = unichr(key) try: ch = unichr(int(unicodedata.decomposition(ch).split()[0], 16)) except (IndexError, ValueError): ch = CHAR_REPLACEMENT.get(key, ch) # uncomment the following line if you want to remove remaining # non-ascii characters # if ch >= u"\x80": return None self[key] = ch return ch if sys.version >= "2.5": __missing__ = mapchar else: __getitem__ = mapchar assert isinstance(mystring, unicode) print mystring.translate(unaccented_map()) ### if the source string is not unicode, you can use something like s = mystring.decode("iso-8859-1") s = s.translate(unaccented_map()) s = s.encode("ascii", "ignore") (this works well for characters in the latin-1 range, at least. no guarantees for other character ranges) -- http://mail.python.org/mailman/listinfo/python-list
Attempting to get lighttpd, fastcgi & python working
Hi folks, I'm trying to get lighttpd, fastcgi & python working on a 2.4.21.x i686 linux system. I tried following the steps in: http://www.cleverdevil.org/computing/24/python-fastcgi-wsgi-and-lighttpd Some of the lighttpd.conf setting are slightly different from those in that article - fixing some erros in the original and accounting for some change in entry formats itself. All components were built by 'root' and binaries run by 'root'. Python files (.py(c)) were deployed to '/site-packages' and run with execute prop turned on. I'm trying to run lighttpd on "dev-1686linux.my.org:8090" with the fastcgi server setup to listen on "127.0.0.1:8091". The problem I'm having is that though lighttpd comes up and is able to serve static content, it fails to bring up the WSGIServer and serve dynamic content (simple "Hello World") generated by the py script (test.pcgi). The errors I get are: [EMAIL PROTECTED] myApp]# lighttpd -f ./lighttpd.conf [EMAIL PROTECTED] myApp]# Traceback (most recent call last): File "/test/myApp/htdocs/test.fcgi", line 21, in ? WSGIServer(myapp, bindAddress = ("127.0.0.1", 8091)).run() File "/usr/lib/python2.4/site-packages/fcgi.py", line 1064, in run sock = self._setupSocket() Traceback (most recent call last): File "/test/myApp/htdocs/test.fcgi", line 21, in ? WSGIServer(myapp, bindAddress = ("127.0.0.1", 8091)).run() File "/usr/lib/python2.4/site-packages/fcgi.py", line 1027, in _setupSocket sock.bind(self._bindAddress) File "/usr/lib/python2.4/site-packages/fcgi.py", line 1064, in run sock = self._setupSocket() File "/usr/lib/python2.4/site-packages/fcgi.py", line 1027, in _setupSocket sock.bind(self._bindAddress) File "", line 1, in bind socket.error: (98, 'Address already in use') File "", line 1, in bind socket.error: (98, 'Address already in use') ... It is unclear why it thinks the 127.0.0.1:8091 sock is already in use. I ran this the first thing after a system reboot. No other apps are using this port. I see this error no matter what port I choose, on the server side. The browser sits there spinning and 'waiting' for the response to url that incudes the .pcgi script. The behviour is slightly different when I use UDSockets to listen on. Again, I can see static content. When I try the py script, I see it waiting indefinitely, but this time no errors are logged into the log file. So no clue where it is hanging on the server side. The access logs are not showing any "request" related entries even for the static content that is being deliverd (albeit properly). Can someone shed light on this. I thought if I can iron out this kink, then I can get TurboGears (CherryPy ws) working with lighttpd and fastcgi proxy-ing upfront. Searched around quite a bit, but unable to find a clue. Would much appreciate some pointers... Thanks a lot ... /venkat Following are the various config settings: /test/myApp/lightpd.conf: - server.modules = ( "mod_rewrite", "mod_access", "mod_fastcgi", "mod_accesslog" ) server.document-root = "/test/myApp/htdocs/" server.errorlog= "/var/tmp/lighttpd.error.log" index-file.names = ( "index.html", "index.htm" ) server.port= 8090 server.bind= "dev-1686linux.my.org" server.error-handler-404 = "/test.fcgi" fastcgi.server = ( ".fcgi" => ( ( "host" => "127.0.0.1", "port" => 8091, "bin-path" => "/test/myApp/htdocs/test.fcgi", "min-procs" => 1 ) ) ) /test/myApp/htdocs/test.fcgi: - #!/usr/bin/python2.4 # test.fcgi for myApp from fcgi import WSGIServer def myapp(environ, start_response): print 'got request: %s' % environ start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello World!\n'] # use a tcp-socket based approach WSGIServer(myapp, bindAddress = ("127.0.0.1", 8091)).run() /test/myApp/fcgi.py: The WSCGIServer (fcgi.py) authored by Saddi is from: http://svn.saddi.com/py-lib/trunk/fcgi.py No mods here. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Creating condensed expressions
Nevermind, I didn't understand the problem/question... Sorry. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Creating condensed expressions
Bruno Desthuilliers a écrit : > David Hirschfield a écrit : > >> Here's the problem: (snip) >> >> is there an efficient algorithm to create condensed forms that match >> those items, Sorry, answered to fast... Well, at least you have a way to test the algo !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Creating condensed expressions
David Hirschfield a écrit : > Here's the problem: Given a list of item names like: > > apple1 > apple2 > apple3_SD > formA > formB > formC > kla_MM > kla_MB > kca_MM > > which is a subset of a much larger list of items, > is there an efficient algorithm to create condensed forms that match > those items, and only those items? Such as: > > apple[12] > apple3_SD > form[ABC] > kla_M[MB] > kca_MM > The condensed expression syntax only has [...] and * as operators. [...] > matches a set of individual characters, * matches any string. > I'd be satisfied with a solution that only uses the [...] syntax, since > I don't think it's possible to use * without potentially matching items > not explicitly in the given list. > > I'm not sure what this condensed expression syntax is called (looks a > bit like shell name expansion syntax), Looks like a very restricted subset of regular expressions. > and I'm not even sure there is an > efficient way to do what I'm asking. Any ideas would be appreciated. import re lines = """ apple1 apple2 apple3_SD formA formB formC kla_MM kla_MB kca_MM """.strip().split() patterns = [ r'apple[12]', r'apple3_SD', r'form[ABC]', r'kla_M[MB]', r'kca_MM', ] for pat in patterns: for line in lines: m = re.match(pat, line) print "%s match %s : %s" % (pat, line, m and "Yes" or 'No') HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Creating condensed expressions
This is a first try, is something like this enough for you? data = """apple1 apple2 apple3_SD formA formB formC kla_MM kla_MB kca_MM""".split() headtails = {} for word in data: head = word[:-1] if head in headtails: headtails[head].append(word[-1]) else: headtails[head] = [word[-1]] for head, tails in sorted(headtails.iteritems()): if len(tails) == 1: print head + tails[0] else: print head + "[%s]" % "".join(tails) Output: apple[12] apple3_SD form[ABC] kca_MM kla_M[MB] It looks only the last letters. It modifies the original order (it sorts the sequence on the root-word). If you don't need sorted results you can remove the sorted(). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
In message <[EMAIL PROTECTED]>, flamesrock <[EMAIL PROTECTED]> writes >I agree, Kate is a great linux editor! > >On windows, I'd have to say notepad2- kate for windows > Well, Notepad might be a bare-bones. I enjoy using UltraEdit, though not UEStudio (the IDE version). You can include a "wordfile" to get Python syntax recognition. Tools are user configurable globally or by project - my first three global tools are Check (with pychecker), Test and Run Regards Ian -- Ian Parker -- http://mail.python.org/mailman/listinfo/python-list
Re: New development windows, IronPython or PythonWin
Dan a écrit : >>>IronPython is currently nowhere near production quality. I would not >>>recommend it. > > I realise its in beta. But long term, do you think that the win32com, > win32gui etc... will have no support because everyone jumps on the > Microsoft bandwagon? Aren't the windows support extensions supported > primarily by one guy, Mark Hammond? As a developer, this seams to leave > me with a vulnerability long term. Thanks for the advise. > Well, from what we've seen so far, I'd rather rely on open source software than on proprietary one. An oss project lives as long as someone is willing to maintain it, and anyone can pick it up. And I wouldn't count on "every one jumping on MS wagon" neither. Just my cents... -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
"Christoph Zwerschke" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Anyway this would be an argument only against the variant of typecasting a > float with a fractional part. But what about the other variant which > raises an error if there is a fractional part, but works if the float is > actually an exact integer, like the result of 4.0//2. I think that's a really bad idea, because of the possibility that the result might happen to be an exact integer on one implementation but not another. In such situations, the fact that it might fail on implementation X may well be impossible to detect by any amount of testing on implementation Y. Such untestable errors are such a nuisance that it would better for the language to encourage programmers to give them a wide berth. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
Wildemar Wildenburger wrote: > just to bloat this thread some more: > > Am I the only one using jEdit? I've yet to find better for developing in jython -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python logo in high resolution format
How about we all get tatoos? : ) Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding problems (é and è)
On 24/03/2006 11:44 PM, Peter Otten wrote: > John Machin wrote: > > >>0x00d0: ord('D'), # Ð >>0x00f0: ord('o'), # ð >>Icelandic capital eth becomes D, OK; but the small letter becomes o!!! > > > I see information flow from Iceland is a bit better than from Armenia :-) No information flow needed. Capital letter BLAH -> D and small letter BLAH -> o should trigger one's palpable nonsense detector for *any* BLAH. > > >>Some of the transformations are a little unfortunate :-( > > > The OP, as you pointed out in your first post in this thread, has more > pressing problems with his normalization approach. > > Lastly, even if all went well, turning a list of French addresses into an > ascii-uppercase graveyard would be a sad thing to do... Oh indeed. Not only sad, but incredibly stupid. I fervently hope and trust that such a normalisation is intended only for fuzzy matching purposes. I can't imagine that anyone would contemplate writing the output to storage for any reason other than logging or for regression testing. Update it back to the database? Do you know anyone who would do that?? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
Was actually going to throw in jEdit for the category of what's good on both platforms... For someone who despises Java, I actually like it. :-) Harlin -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
Been using PyDev plugin for Eclipse for a week now... works pretty good, and integrates well with PyLint. Has some context-sensitive help, but not much. I wonder if writing a script to convert Python HTML docs to Javadoc format would help? H maybe I'll ask. -- http://mail.python.org/mailman/listinfo/python-list
Help: Creating condensed expressions
Here's the problem: Given a list of item names like: apple1 apple2 apple3_SD formA formB formC kla_MM kla_MB kca_MM which is a subset of a much larger list of items, is there an efficient algorithm to create condensed forms that match those items, and only those items? Such as: apple[12] apple3_SD form[ABC] kla_M[MB] kca_MM The condensed expression syntax only has [...] and * as operators. [...] matches a set of individual characters, * matches any string. I'd be satisfied with a solution that only uses the [...] syntax, since I don't think it's possible to use * without potentially matching items not explicitly in the given list. I'm not sure what this condensed expression syntax is called (looks a bit like shell name expansion syntax), and I'm not even sure there is an efficient way to do what I'm asking. Any ideas would be appreciated. Thanks, -David -- Presenting: mediocre nebula. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
just to bloat this thread some more: Am I the only one using jEdit? (really, I never see it mentioned anywhere ...) wildemar -- http://mail.python.org/mailman/listinfo/python-list