Re: Iteration over recursion?
You might use a separate prime generator to produce prime factors. The factorize algorithm becomes quite simple and configurable by prime generators. For demonstration purposes I use the eratosthenes sieve. def eratosthenes(): memo = {} q = 2 while True: p = memo.pop(q, None) if p is None: yield q memo[q*q] = q else: x = p + q while x in memo: x += p memo[x] = p q+=1 def factorize(n, sieve = eratosthenes): if n <= 1: return [n] factors = [] primes = sieve() for q in primes: while n % q == 0: factors.append(q) n //= q if n == 1: return factors Regards, Kay -- http://mail.python.org/mailman/listinfo/python-list
Python SHA-1 as a method for unique file identification ? [help!]
This inquiry may either turn out to be about the suitability of the SHA-1 (160 bit digest) for file identification, the sha function in Python ... or about some error in my script. Any insight appreciated in advance. I am trying to reduce duplicate files in storage at home - I have a large number files (e.g. MP3s) which have been stored on disk multiple times under different names or on different paths. The using applications will search down from the top path and find the files - so I do not need to worry about keeping track of paths. All seemed to be working until I examined my log files and found files with the same SHA digest had different sizes according to os.stat(fpath).st_size . This is on Windows XP. - Am I expecting too much of SHA-1? - Is it that the os.stat data on Windows cannot be trusted? - Or perhaps there is a silly error in my code I should have seen? Thanks - Eric - - - - - - - - - - - - - - - - - - Log file extract: Dup: noPath: F:\music\mp3s\01125.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 01125.mp3Size: 63006 Dup: YESPath: F:\music\mp3s\0791.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0791.mp3Size: 50068 Dup: YESPath: F:\music\mp3s\12136.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 12136.mp3Size: 51827 Dup: YESPath: F:\music\mp3s\11137.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 11137.mp3Size: 56417 Dup: YESPath: F:\music\mp3s\0991.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0991.mp3Size: 59043 Dup: YESPath: F:\music\mp3s\0591.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0591.mp3Size: 59162 Dup: YESPath: F:\music\mp3s\10140.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 10140.mp3Size: 59545 Dup: YESPath: F:\music\mp3s\0491.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0491.mp3Size: 63101 Dup: YESPath: F:\music\mp3s\0392.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0392.mp3Size: 63252 Dup: YESPath: F:\music\mp3s\0891.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0891.mp3Size: 65808 Dup: YESPath: F:\music\mp3s\0691.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0691.mp3Size: 67050 Dup: YESPath: F:\music\mp3s\0294.mp3Hash: 00b3acb529aae11df186ced8424cb189f062fa48Name: 0294.mp3Size: 67710 Code: # Dedup_inplace.py # vers .02 # Python 2.4.1 # Create a dictionary consisting of hash:path # Look for 2nd same hash and delete path testpath=r"F:\music\mp3s" logpath=r"C:\testlog6.txt" import os, sha def hashit(pth): """Takes a file path and returns a SHA hash of its string""" fs=open(pth,'r').read() sh=sha.new(fs).hexdigest() return sh def logData(d={}, logfile="c://filename999.txt", separator="\n"): """Takes a dictionary of values and writes them to the provided file path""" logstring=separator.join([str(key)+": "+d[key] for key in d.keys()])+"\n" f=open(logfile,'a') f.write(logstring) f.close() return def walker(topPath): fDict={} logDict={} limit=1000 freed_space=0 for root, dirs, files in os.walk(topPath): for name in files: fpath=os.path.join(root,name) fsize=os.stat(fpath).st_size fkey=hashit(fpath) logDict["Name"]=name logDict["Path"]=fpath logDict["Hash"]=fkey logDict["Size"]=str(fsize) if fkey not in fDict.keys(): fDict[fkey]=fpath logDict["Dup"]="no" else: #os.remove(fpath) --uncomment only when script proven logDict["Dup"]="YES" freed_space+=fsize logData(logDict, logpath, "\t") items=len(fDict.keys()) print "Dict entry: ",items, print "Cum freed space: ",freed_space if items > limit: break if items > limit: break def emptyNests(topPath): """Walks downward from the given path and deletes any empty directories""" for root, dirs, files in os.walk(topPath): for d in dirs: dpath=os.path.join(root,d) if len(os.listdir(dpath))==0: print "deleting: ", dpath os.rmdir(dpath) walker(testpath) emptyNests(testpath) -- http://mail.python.org/mailman/listinfo/python-list
Re: Initializing a set from a list
Sybren Stuvel wrote: > Xiaolei enlightened us with: > > from pylab import * > > You'd better not do that. Just use "import pylab". > > > If I remove the first line, I correctly get: > > > > [1, 2, 3, 3] > > > > set([1, 2, 3]) > > Pylab shadows the built-in set name, which is one of the reasons you > should generally use "import XXX" instead of "from XXX import *". Ahh. Understood. Thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python SHA-1 as a method for unique file identification ? [help!]
EP wrote: > This inquiry may either turn out to be about the suitability of the > SHA-1 (160 bit digest) for file identification, the sha function in > Python ... or about some error in my script. > > This is on Windows XP. > > def hashit(pth): > fs=open(pth,'r').read() > sh=sha.new(fs).hexdigest() > return sh > cannot comment on the suitability of SHA for your use-case but shouldn't you be opening the file in binary mode? fs=open(pth,'rb').read() -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Marshall wrote: > Joe Marshall wrote: > >>They *do* have a related meaning. Consider this code fragment: >>(car "a string") >>[...] >>Both `static typing' and `dynamic typing' (in the colloquial sense) are >>strategies to detect this sort of error. > > > The thing is though, that putting it that way makes it seems as > if the two approaches are doing the same exact thing, but > just at different times: runtime vs. compile time. But they're > not the same thing. Passing the static check at compile > time is universally quantifying the absence of the class > of error; passing the dynamic check at runtime is existentially > quantifying the absence of the error. A further difference is > the fact that in the dynamically typed language, the error is > found during the evaluation of the expression; in a statically > typed language, errors are found without attempting to evaluate > the expression. > > I find everything about the differences between static and > dynamic to be frustratingly complex and subtle. Let me add another complex subtlety, then: the above description misses an important point, which is that *automated* type checking is not the whole story. I.e. that compile time/runtime distinction is a kind of red herring. In fact, automated type checking is orthogonal to the question of the existence of types. It's perfectly possible to write fully typed programs in a (good) dynamically-checked language. In a statically-checked language, people tend to confuse automated static checking with the existence of types, because they're thinking in a strictly formal sense: they're restricting their world view to what they see "within" the language. Then they look at programs in a dynamically-checked language, and see checks happening at runtime, and they assume that this means that the program is "untyped". It's certainly close enough to say that the *language* is untyped. One could also say that a program, as seen by the language, is untyped. But a program as seen by the programmer has types: the programmer performs (static) type inference when reasoning about the program, and debugs those inferences when debugging the program, finally ending up with a program which has a perfectly good type scheme. It's may be messy compared to say an HM type scheme, and it's usually not proved to be perfect, but that again is an orthogonal issue. Mathematicians operated for thousands of years without automated checking of proofs, so you can't argue that because a dynamically-checked program hasn't had its type scheme proved correct, that it somehow doesn't have types. That would be a bit like arguing that we didn't have Math until automated theorem provers came along. These observations affect the battle over terminology in various ways. I'll enumerate a few. 1. "Untyped" is really quite a misleading term, unless you're talking about something like the untyped lambda calculus. That, I will agree, can reasonably be called untyped. 2. "Type-free" as suggested by Chris Smith is equally misleading. It's only correct in a relative sense, in a narrow formal domain which ignores the process of reasoning about types which is inevitably performed by human programmers, in any language. 3. A really natural term to refer to types which programmers reason about, even if they are not statically checked, is "latent types". It captures the situation very well intuitively, and it has plenty of precedent -- e.g. it's mentioned in the Scheme reports, R5RS and its predecessors, going back at least a decade or so (haven't dug to check when it first appeared). 4. Type theorists like to say that "universal" types can be used in a statically-typed language to subsume "dynamic types". Those theorists are right, the term "dynamic type", with its inextricable association with runtime checks, definitely gets in the way here. It might be enlightening to rephrase this: what's really happening is that universal types allow you to embed a latently-typed program in a statically-checked language. The latent types don't go anywhere, they're still latent in the program with universal types. The program's statically-checked type scheme doesn't capture the latent types. Describing it in these terms clarifies what's actually happening. 5. Dynamic checks are only part of the mechanism used to verify latent types. They shouldn't be focused on as being the primary equivalent to static checks. The closest equivalent to the static checks is a combination of human reasoning and testing, in which dynamic checks play an important but ultimately not a fundamental part. You could debug a program and get the type scheme correct without dynamic checks, it would just be more difficult. So, will y'all just switch from using "dynamically typed" to "latently typed", and stop talking about any real programs in real programming languages as being "untyped" or "type-free", unless you really are t
Re: Iteration over recursion?
In article <[EMAIL PROTECTED]>, "Kay Schluehr" <[EMAIL PROTECTED]> writes: |> |> You might use a separate prime generator to produce prime factors. The |> factorize algorithm becomes quite simple and configurable by prime |> generators. For demonstration purposes I use the eratosthenes sieve. That is a good point. The differences between iteration and recursion are well-understood (by some people, at least), but the difference between those two and generators is not. I have mixed feelings whether they are a good idea or not, largely because I have never seen a language that provides a declaration to guarantee that a generator is 'clean'. And an unclean generator (e.g. one with side-effects) is a most revolting object, from a software engineering (including validation) point of view. One good example of this is streaming input (I/O). Traditional, clean streaming input can be implemented efficiently and with good error diagnostics. The unclean C- and POSIX-like streaming input can't be, or at least only one of the two can be provided at once. Regards, Nick Maclaren. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
David Hopwood wrote: > Pascal Costanza wrote: >> Rob Thorpe wrote: >>> Pascal Costanza wrote: Matthias Blume wrote: > Pascal Costanza <[EMAIL PROTECTED]> writes: > >> (slot-value p 'address) is an attempt to access the field 'address in >> the object p. In many languages, the notation for this is p.address. >> >> Although the class definition for person doesn't mention the field >> address, the call to (eval (read)) allows the user to change the >> definition of the class person and update its existing >> instances. Therefore at runtime, the call to (slot-value p 'adress) >> has a chance to succeed. > I am quite comfortable with the thought that this sort of evil would > get rejected by a statically typed language. :-) This sort of feature is clearly not meant for you. ;-P >>> To be fair though that kind of thing would only really be used while >>> debugging a program. >>> Its no different than adding a new member to a class while in the >>> debugger. >>> >>> There are other places where you might add a slot to an object at >>> runtime, but they would be done in tidier ways. >> Yes, but the question remains how a static type system can deal with >> this kind of updates. > > It's not difficult in principle: > > - for each class [*], define a function which converts an 'old' value of >that class to a 'new' value (the ability to do this is necessary anyway >to support some kinds of upgrade). A default conversion function may be >autogenerated if the class definition has changed only in minor ways. Yep, this is more or less exactly how CLOS does it. (The conversion function is called update-instance-for-redefined-class, and you can provide your own methods on it.) > - typecheck the new program and the conversion functions, using the old >type definitions for the argument of each conversion function, and the >new type definitions for its result. The problem here is: The program is already executing, so this typecheck isn't performed at compile-time, in the strict sense of the word (i.e., before the program is deployed). It may still be a syntactic analysis, but you don't get the kind of guarantees anymore that you typically expect from a static type checker _before_ the program is started in the first place. (It's really important to understand that the idea is to use this for deployed programs - albeit hopefully in a more structured fashion - and not only for debugging. The example I have given is an extreme one that you would probably not use as such in a "real-world" setting, but it shows that there is a boundary beyond which static type systems cannot be used in a meaningful way anymore, at least as far as I can tell.) > - have the debugger apply the conversions to all values, and then resume >the program. In CLOS, this conversion is defined as part of the language proper, but this is mostly because Common Lisp doesn't make a sharp distinction between debugging capabilities and "regular" language features. (I think it's a good thing that there is no strong barrier against having debugging capabilities in a deployed program.) > [*] or nearest equivalent in a non-OO language. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to truncate/round-off decimal numbers?
Hi, just a thought: if you *always* work with "floats" with two decimals, you are in fact working with integers, but you represent them as a floats - confusing for the internal representation. So why not work with int(float * 100) instead? This way you only have to take care of roundoffs etc when dividing. "int (+|-|*) int" = int "int / int" = int / int + int % int Integers are nice, me like integers. /per9000 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to truncate/round-off decimal numbers?
oops, should be something like this: "int / int" = "int / int, int % int" /per9000 -- http://mail.python.org/mailman/listinfo/python-list
wxStyledTextCtrl and sql syntax highlightning
Hi. I use wxPy version 2.4.2 for Python 2.3. Now I wanted to use the wxStyledTextCtrl for viewing (editing) of sql code. I have the following: self.__m_styled_text_ctrl = wxPython.stc.wxStyledTextCtrl( self, wx.NewId(), style=wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE) self.__m_styled_text_ctrl.SetLexer(wxPython.stc.wxSTC_LEX_SQL) self.__m_styled_text_ctrl.SetProperty("fold", "1") self.__m_styled_text_ctrl.SetMargins(0,0) self.__m_styled_text_ctrl.SetKeyWords(0, SQL_KEYWORDS) Where sql_keywords is string with space separated sql keywords. When i add text to the ctrl i don't get the right highlightning. What do i do wrong and what else do i have to specify? thx in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic inheritance
alf wrote: > I did not think about any particular problem, just thought it would be > cool to abstract out the base class. In fact you can do that in C++ (to > some extend) using templates and parameterizing the base class. Python is ways cooler than C++. This is a sensible use case where you may want to change the base class at runtime: >>> class Base(object): ... pass >>> class BasePlusDebugMethods(Base): ... pass ... >>> class C(Base): ... pass >>> C.__bases__ = (BasePlusDebugMethods,) >>> C.mro() [, , , ] (i.e. in a running program with a problem you can add debug methods and possibily even fix the problem without restarting the program). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Are any python-LVM bindings available?
I need to execute LVM operations from within python ... are there any packages containing direct bindings available or is forking a shell the only solution? Any thoughts would be much appreciated. cheers. -- http://mail.python.org/mailman/listinfo/python-list
Search substring in a string and get index of all occurances
Hi there, I would like to search for a substring in a string and get the index of all occurances. mystring = 'John has a really nice powerbook.' substr = ' ' # space I would like to get this list: [4, 8, 10, 17, 22] How can I do that without using "for i in mystring" which might be expensive for large strings? Thanks in advance, Nico -- http://mail.python.org/mailman/listinfo/python-list
Re: Python SHA-1 as a method for unique file identification ? [help!]
[EP <[EMAIL PROTECTED]>] > This inquiry may either turn out to be about the suitability of the > SHA-1 (160 bit digest) for file identification, the sha function in > Python ... or about some error in my script It's your script. Always open binary files in binary mode. It's a disaster on Windows if you don't (if you open a file in text mode on Windows, the OS pretends that EOF occurs at the first instance of byte chr(26) -- this is an ancient Windows behavior that made an odd kind of sense in the mists of history, and has persisted in worship of Backward Compatibility despite that the original reason for it went away _long_ ago). ... > I am trying to reduce duplicate files in storage at home - I have a > large number files (e.g. MP3s) which have been stored on disk multiple > times under different names or on different paths. ... > All seemed to be working until I examined my log files and found files > with the same SHA digest had different sizes according to > os.stat(fpath).st_size . This is on Windows XP. > > - Am I expecting too much of SHA-1? No. SHA-1 should work well for this. > - Is it that the os.stat data on Windows cannot be trusted? It can be trusted to the extent that anything on Windows can be trusted ;-) ... > def hashit(pth): > """Takes a file path and returns a SHA hash of its string""" > fs=open(pth,'r').read() Make that 'rb' instead of 'r', and your problem will go away. Do note that there are faster ways to go about this. For example, if a particular file has a unique size among the files you're looking at, there's no reason to even open that file (let alone compute its hash). Group the files by size, and within a size group you can find duplicates by, e.g., first comparing their initial 16 bytes, then the next 32, then the next 64 ... etc. If duplicates are uncommon, this can be a huge savings. For example, here's output from an old dup-finding Python program of mine run over a directory tree which happens to contain no duplicates: Files - Total 10,718 Unique 10,718 Duplicate0 # w/ unique size10,053 # w/ unique prefix 665 Bytes - Total 1,401,668,015 Unique 1,401,668,015 Duplicate 0 Read 76,688 Excess76,688 That last two lines mean it actually read a total of only about 77,000 file bytes on its way to proving there were no duplicates among about 11,000 files spanning about 1.4 gigabytes. No hashes are computed by that program. I'd use a hash if instead I were going to save a persistent (across runs) set of known hashes, so that answering "here's a new file -- same as one I already have?" could be done by computing its hash. While the program above generally reads "amazingly" few file bytes, it hammers the OS file directory services, and it would go faster to compute a hash of a new file than to run the whole analysis again. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to truncate/round-off decimal numbers?
> just a thought: if you *always* work with "floats" with two decimals, > you are in fact working with integers, but you represent them as a > floats - confusing for the internal representation. > > So why not work with int(float * 100) instead? This way you only have > to take care of roundoffs etc when dividing. And why won't you work with decimal module ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
mystring = 'John has a really nice powerbook.' substr = ' ' # space pos = 0 indices = [] while True: i = mystring.find(substr,pos) if i==-1: break indices.append(i) pos = i+1 print indices > [4, 8, 10, 17, 22] Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: wxStyledTextCtrl and sql syntax highlightning
> I have the following: > self.__m_styled_text_ctrl = wxPython.stc.wxStyledTextCtrl( > self, wx.NewId(), > style=wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE) > self.__m_styled_text_ctrl.SetLexer(wxPython.stc.wxSTC_LEX_SQL) > self.__m_styled_text_ctrl.SetProperty("fold", "1") > self.__m_styled_text_ctrl.SetMargins(0,0) > self.__m_styled_text_ctrl.SetKeyWords(0, SQL_KEYWORDS) Hi Pierre, I'd like to do some tests with your stuff, but I'd appreciate to have a working sample. Would you like to post it ? Regards, jm -- http://mail.python.org/mailman/listinfo/python-list
Re: How to truncate/round-off decimal numbers?
In article <[EMAIL PROTECTED]>, "per9000" <[EMAIL PROTECTED]> writes: |> |> just a thought: if you *always* work with "floats" with two decimals, |> you are in fact working with integers, but you represent them as a |> floats - confusing for the internal representation. No, you aren't - you are working with fixed-point, which is something that is neither integers nor floating-point, but is somewhere in between. I am (just) old enough to remember when it was used for numeric work, and to have used it for that myself, but not old enough to have done any numeric work using fixed-point hardware. |> So why not work with int(float * 100) instead? This way you only have |> to take care of roundoffs etc when dividing. And multiplying, and calling most mathematical functions. Regards, Nick Maclaren. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is fun (useless social thread) ;-)
BartlebyScrivener wrote: You know what are dicts, right ? That is, containers with keyword-access to values ? Then you probably have dicts with a known, defined structure, and functions working on it. What classes (and hence 00) gives you is a way to associate these functions with the dicts themselves. That is the big intuition about objects, the rest is just details. > > > You bet. No big deal. Using dicts to organize data is quite obvious, and then you need to operate on these data, so you write functions using these dicts... > I have lots of these. > Especially a large dictionary that is > kind of an application and site launcher. I type "l clp" at the command > line, and l.py runs a function def launch(obj), which grabs the key > "clp" whose value is this site address, and I'm browsing clp. Kind of > like favorites with no mouse. Or another dictionary with applications. > Same way. They work fine. I guess they aren't complex enough to require > classes yet? Nothing really *requires* classes if you go that way. Now going from dicts+functions to classes+methods is quite a no-brainer, and can really ease maintenance. Once you'll be there, you'll probably find yourself shifting to a more OO style (small decoupled methods, polymorphic dispatch etc) swithout even noticing. You don't have to learn all the voodoo stuff about OO to start using OO in Python - but if you already made the move from strictly procedural (dicts/lists/tuples + functions) to ADTs (simplest use of classes), you'll be happy to have the whole power of Python's object model when the need arise. > I appreciate the tips. I'll do a couple tutorials and read my books and > then come back with any OO questions. You're welcome. FWIW, a good exercice would be to take one of your own programs and try to gradually transform dicts+related funcs to classes. My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
OT: wxPython GUI designer
"Don Taylor" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I find it easy to use sizers in > wxGlade. Just gave is a spin yesterday: How does on fix the size of layout; I can only manage to get sizers to distribute space evently amongst the fields, which is *not* what I want. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
"Rob Thorpe" <[EMAIL PROTECTED]> writes: > Andreas Rossberg wrote: > > > No, variables are insignificant in this context. You can consider a > > language without variables at all (such languages exist, and they can > > even be Turing-complete) and still have evaluation, values, and a > > non-trivial type system. > > Hmm. You're right, ML is no-where in my definition since it has no > variables. That's not true. ML has variables in the mathematical sense of variables -- symbols that can be associated with different values at different times. What it doesn't have is mutable variables (though it can get the effect of those by having variables be immutable references to mutable memory locations). What Andreas was alluding to was presumably FP-style languages where functions or relations are built by composing functions or relations without ever naming values. Torben -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifing arguments type for a function
Paolo Pantaleo wrote: > I have a function > > def f(the_arg): > ... > > and I want to state that the_arg must be only of a certain type > (actually a list). Is there a way to do that? I wrote a cool function decorator just for that purpose. It's posted on the Python Decorator Library at: http://wiki.python.org/moin/PythonDecoratorLibrary#head-308f2b3507ca91800def19d813348f78db34303e If you use it, you will be able to simply write: @accepts(list) def f(the_arg): ... and you will get a warning message if the_arg is not a list. Or, if you want an exception raised, then just: @accepts(list, debug=2) def f(the_arg): ... Let me know what you think, if you do end up using it. I'm eager for feedback. -- http://mail.python.org/mailman/listinfo/python-list
Re: separation events
Ghido wrote: > Hi all, i'm writing a software with python and wxpython for manage the > quality/environmental/security system for the my factory. I want to > separate the gui structure from the events and database operations for > obtain a very modular software, for this reason i start to use > sqlalchemy. Unfortunately i don't understand if is possibile to have a > file with only the gui structure and another file with the database > operations and the events of the gui. It is possibile? You may want to look for MVC (Model/View/Controller). > the use of > sqlalchemy is a good thing? > Thanks a lot > > Ghido > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
David Hopwood wrote: > > Oh, but it *does* make sense to talk about dynamic tagging in a statically > typed language. It even makes perfect sense to talk about dynamic typing in a statically typed language - but keeping the terminology straight, this rather refers to something like described in the well-known paper of the same title (and its numerous follow-ups): Martin Abadi, Luca Cardelli, Benjamin Pierce, Gordon Plotkin Dynamic typing in a statically-typed language. Proc. 16th Symposium on Principles of Programming Languages, 1989 / TOPLAS 13(2), 1991 Note how this is totally different from simple tagging, because it deals with real types at runtime. - Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Matthias Blume wrote: > "Rob Thorpe" <[EMAIL PROTECTED]> writes: > > > I think we're discussing this at cross-purposes. In a language like C > > or another statically typed language there is no information passed > > with values indicating their type. > > You seem to be confusing "does not have a type" with "no type > information is passed at runtime". > > > Have a look in a C compiler if you don't believe me. > > Believe me, I have. In a C compiler the compiler has no idea what the values are in the program. It knows only their type in that it knows the type of the variable they are contained within. Would you agree with that? > > No it doesn't. Casting reinterprets a value of one type as a value of > > another type. > > There is a difference. If I cast an unsigned integer 20 to a > > signed integer in C on the machine I'm using then the result I will get > > will not make any sense. > > Which result are you getting? What does it mean to "make sense"? Well the right one actually, bad example. But, if I cast an unsigned int 25 to signed I get -1794967296. -- http://mail.python.org/mailman/listinfo/python-list
help() on stdout.closed
Python 2.4.1 (#1, May 16 2005, 15:19:29) [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from sys import stdout >>> help (stdout.closed) If I do this, it gives me help on the bool object. Also: >>> stdout.closed.__doc__ 'bool(x) -> bool\n\nReturns True when the argument x is true, False otherwise.\nThe builtins True and False are the only two instances of the class bool.\nThe class bool is a subclass of the class int, and cannot be subclassed.' What's going on here? Other docstrings in sys.stdout work fine. Pekka (uses 2.4.3 on another comp) -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Rob Thorpe wrote: > > I think this should make it clear. If I have a "xyz" in lisp I know it > is a string. > If I have "xyz" in an untyped language like assembler it may be > anything, two pointers in binary, an integer, a bitfield. There is no > data at compile time or runtime to tell what it is, the programmer has > to remember. You have to distinguish between values (at the level of language semantics) and their low-level representation (at the implementation level). In a high-level language, the latter should be completely immaterial to the semantics, and hence not interesting for the discussion. >>No, variables are insignificant in this context. You can consider a >>language without variables at all (such languages exist, and they can >>even be Turing-complete) and still have evaluation, values, and a >>non-trivial type system. > > Hmm. You're right, ML is no-where in my definition since it has no > variables. Um, it has. Mind you, it has no /mutable/ variables, but that was not even what I was talking about. >>>But the value itself has no type >> >>You mean that the type of the value is not represented at runtime? True, >>but that's simply because the type system is static. It's not the same >>as saying it has no type. > > Well, is it even represented at compile time? > The compiler doesn't know in general what values will exist at runtime, > it knows only what types variables have. Sometimes it only has partial > knowledge and sometimes the programmer deliberately overrides it. From > what knowledge it you could say it know what types values will have. Again, variables are insignificant. From the structure of an expression the type system derives the type of the resulting value. An expression may contain variables, and then the type system generally must know (or be able to derive) their types too, but that's a separate issue. Most values are anonymous. Nevertheless their types are known. > Unfortunately it's often necessary to break static type systems. Your definitely using the wrong static language then. ;-) - Andreas -- http://mail.python.org/mailman/listinfo/python-list
What's the best way to wrap a whole script in try..except?
I want to wrap a whole script in try ... except. What is the best way of doing this? Consider the following: - try: import def notifyme(traceback): code to tell me there is a problem except Exception, traceback: notifyme(traceback) Would this code not work because if any part of encounters an exception then it won't reach the notifyme() function definition and therefore the whole thing won't work and I won't get notified when a traceback occurs, in fact the call to notifyme() under except will itself probably trace back as well! Do I have to instead do: import def notifyme(): code to tell me there is a problem try: except Exception, traceback: notifyme(traceback) How you you handle this? Hari -- http://mail.python.org/mailman/listinfo/python-list
Re: help() on stdout.closed
In article <[EMAIL PROTECTED]>, Pekka Karjalainen wrote: from sys import stdout help (stdout.closed) > > If I do this, it gives me help on the bool object. stdout.closed is a bool. What were you expecting it to show you? -- http://mail.python.org/mailman/listinfo/python-list
Re: help() on stdout.closed
Pekka Karjalainen wrote: from sys import stdout help (stdout.closed) > > If I do this, it gives me help on the bool object. that's probably because "sys.stdout.closed" *is* a bool object: >>> sys.stdout.closed False >>> type(sys.stdout.closed) there's no way the reflection system can figure out how a given boolean was created; all it knows is that it gets an object of a given type. > Other docstrings in sys.stdout work fine. have you tried things like >>> help(sys.stdout.name) and >>> help(sys.stdout.write("hello")) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to wrap a whole script in try..except?
In article <[EMAIL PROTECTED]>, Hari Sekhon wrote: > I want to wrap a whole script in try ... except. What is the best way of > doing this? You could do this maybe: import sys def excepthook(exc_type, exc_value, tb): import modules_needed_to_notify_exception ... sys.excepthook = excepthook import modules_needed_by_script ... -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to wrap a whole script in try..except?
Hari Sekhon wrote: > I want to wrap a whole script in try ... except. What is the best way of > doing this? > > Consider the following: - > > try: >import > > > >def notifyme(traceback): > code to tell me there is a problem > > except Exception, traceback: >notifyme(traceback) > > > Would this code not work because if any part of encounters an > exception then it won't reach the notifyme() function definition and > therefore the whole thing won't work and I won't get notified when a > traceback occurs, in fact the call to notifyme() under except will > itself probably trace back as well! Yes. > Do I have to instead do: > > import > def notifyme(): >code to tell me there is a problem > > try: > > > except Exception, traceback: >notifyme(traceback) > Would work, but... > How you you handle this? I don't put the main logic at the top level - I use a main() function. import def notifyme(e): # code here... def main(*args): try: # code here return 0 except Exception, e: notifyme(e) return if __name__ == '__main__': import sys sys.exit(main(*sys.argv)) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: difference between import from mod.func() and x=mod.func()
I take it that it's not worth listening to that tutorial and just using good old "import from", which I suspect is better anyway since it imports less..."uneducated premature optimisation" - I take it this is insulting a that programmer's progexuality...! "import from" it is then unless anybody has anything else to say on the matter.ThanksHariOn 20/06/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote: Hari Sekhon wrote:> What is the difference in terms of efficiency and speed between>> from os import path>> and>> import os> path=os.paththe only difference is that the former only sets the "path" variable, while the latter leaves both "os" and "path" in your namespace.> I would think that the import from would be better, just curious since I> read somewhere on the web, some guy's code tutorial where he did the > latter and said it was for efficiency/speed.sounds like "uneducated premature optimization" to me.-- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
Nico Grubert wrote: > I would like to search for a substring in a string and get the index of > all occurances. > > mystring = 'John has a really nice powerbook.' > substr = ' ' # space > > I would like to get this list: > [4, 8, 10, 17, 22] the find and index methods take an optional start argument, so the obvious way to do this is to use a simple loop; e.g. result = []; pos = -1 try: while 1: pos = mystring.index(substr, pos+1) result.append(pos) except ValueError: pass # done if you prefer one-liners, you can use the RE engine instead: result = [m.start() for m in re.finditer(re.escape(substr), mystring)] this has a much higher setup overhead, but can be faster than the loop form for some kinds of data (at least in 2.4 and earlier). ...and if you're going to look for the same substring a lot, you can factor out the escape/compile step: substr_scanner = re.compile(re.escape(substr)).finditer result = [m.start() for m in substr_scanner(mystring)] if you're not 100% sure you need all the matches later on, you can use a generator expression instead of the list comprehension: result = (m.start() for m in re.finditer(re.escape(substr), mystring)) ... for pos in result: ... if pos > 1000: break # won't need the rest hope this helps! -- http://mail.python.org/mailman/listinfo/python-list
Re: WinPops
If you were going to do this you may as well just do something likeif sys.platform='win32': os.system('net send ')elif sys.platform[:5]='linux' os.system('smblcient -M etc...') This would be more portable and simpler than the alternatives I've seen. It would be better if there was just a cross platform library for this protocol so you could justimport winpopwinpop.send (host,message)Too much to ask?HariOn 01/06/06, Peter Gsellmann <[EMAIL PROTECTED] > wrote:Roger Upole wrote:>> "Hari Sekhon" < [EMAIL PROTECTED]> wrote in message> news:[EMAIL PROTECTED]>> Hi,>> Is there a way of sending winpops (Windows Pop-Up / Net Send messages) >> in python? Perhaps some library or something that I can use under both Windows and>> Linux? Hari>> On Windows, you can use win32net.NetMessageBufferSend .>> Roger>On Linux, i use the smbclient binary: from subprocess import * q=Popen(['smbclient','-M','maggy'],stdin=PIPE) q.stdin.write('hello!') q.stdin.close() q.wait ()Peter--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: wxStyledTextCtrl and sql syntax highlightning
Hi. Thanks it works now .. i must reset the default styles with StyleClearAll and then set the styles apropriate again. Is there a way that the keyword list isn't case sensitive, as sql isn't. reg, Pierre jean-michel bain-cornu wrote: > > I have the following: > > self.__m_styled_text_ctrl = wxPython.stc.wxStyledTextCtrl( > > self, wx.NewId(), > > style=wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE) > > self.__m_styled_text_ctrl.SetLexer(wxPython.stc.wxSTC_LEX_SQL) > > self.__m_styled_text_ctrl.SetProperty("fold", "1") > > self.__m_styled_text_ctrl.SetMargins(0,0) > > self.__m_styled_text_ctrl.SetKeyWords(0, SQL_KEYWORDS) > Hi Pierre, > I'd like to do some tests with your stuff, but I'd appreciate to have a > working sample. Would you like to post it ? > Regards, > jm -- http://mail.python.org/mailman/listinfo/python-list
Re: memory error with zipfile module
On 20/05/06, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: Roger Miller a écrit :> The basic problem is that the zipfile interface only reads and writes> whole files, so it may perform poorly or fail on huge files. At one> time I implemented a patch to allow reading files in chunks. However I > believe that the current interface has too many problems to solve by> incremental patching,Yeps, that was the general tone of some thread on python-dev. And fromwhat I saw of the source code, it may effectively not be the cleanest part of the stdlib. But what, it does what it was written for at first :provide working support for zipped packages.> and that a zipfile2 module is probably warranted.> (Is anyone working on this?) Seems like Bob Ippolito was on the rank, but I guess you'll get betteranswers on python-dev.> In the meantime I think the best solution is often to just run an> external zip/unzip utility to do the heavy lifting. Indeed !-)But while having zip/unzip installed OOTB on a unix-like system is closeto warrented, it may not be the case on Windows.-- http://mail.python.org/mailman/listinfo/python-listShame, I would like to try to improve this but seeing as Roger Miller has already submitted a patch I don't know how much I can do for this. In the end I resorted to using an external zip utility via os.system().I'll be interested to know if there is any work done on improving this as I'm in favour of native python usage, rather than using os.system() and relying on the operating system having a zip command, which I'm not convinced is the case on all windows machines, and also, I'm sure gentoo installs don't have zip by default, since I had to emerge it on a server for this script to work. Is it me or is having to use os.system() all the time symtomatic of a deficiency/things which are missing from python as a language? Not that I'm complaining, I'm just curious... I'm a fledgeling programmer so I don't mind being gently corrected by any veterans around. Hari -- http://mail.python.org/mailman/listinfo/python-list
embedded Python calling app via COM
I have a C++ app which fires up a Python script using C API calls. That script operates the app via Automation calls, like this: from win32com.client import * from mywrapper import * myapp = Application() myapp.Visible = True mydoc = myapp.Documents.Open(...) My problem is to make sure the instance of myapp is the same one I am calling from. The above code starts up a new instance of the app, which is not what I want. In other words I need something like a GetObject instead of a CreateObject, and I need some way to identify the calling app so I can tell GetObject about it. Before I go and do something hack, I thought I'd see if anyone else is in this situation and knows a good way to do the job. -- Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Andreas Rossberg schrieb: > Rob Thorpe wrote: >> Hmm. You're right, ML is no-where in my definition since it has no >> variables. > > Um, it has. Mind you, it has no /mutable/ variables, but that was not > even what I was talking about. Indeed. A (possibly nonexhaustive) list of program entities that (can) have type would comprise of mutable variables, immutable variables (i.e. constants and parameter names), and functions resp. their results. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Matthias Blume schrieb: > Joachim Durchholz <[EMAIL PROTECTED]> writes: > >> Matthias Blume schrieb: >>> Perhaps better: A language is statically typed if its definition >>> includes (or ever better: is based on) a static type system, i.e., a >>> static semantics with typing judgments derivable by typing rules. >>> Usually typing judgmets associate program phrases ("expressions") with >>> types given a typing environment. >> This is defining a single term ("statically typed") using three >> undefined terms ("typing judgements", "typing rules", "typing >> environment"). > > This was not meant to be a rigorous definition. Rigorous or not, introducing additional undefined terms doesn't help with explaining a term. > Also, I'm not going to repeat the textbook definitions for those > three standard terms here. These terms certainly aren't standard for Perl, Python, Java, or Lisp, and they aren't even standard for topics covered on comp.lang.functional (which includes dynamically-typed languages after all). Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: How to truncate/round-off decimal numbers?
Nick Maclaren wrote: > |> just a thought: if you *always* work with "floats" with two decimals, > |> you are in fact working with integers, but you represent them as a > |> floats - confusing for the internal representation. > > No, you aren't - you are working with fixed-point Nick, your answer has so many layers, I'll try to explain how I think :-D 1) if you use integers you can think of them as having one part bigger than 100 and one part smaller than 100, like so: >>> a = 11122 >>> (a/100,a%100) (111, 22) Here the output 111,22 looks like something else than an integer, but this is just a matter of representation. a *is* an integer, but we represent it *as if it was* a "decimal" number. (Compare with (minutes,seconds) or (euro,cents) or (feet,inch) or any other "arbitrary" position system) 2) If we use floats with two decimals >>> b = 222.33 >>> b 222.330001 they look like fix-point numbers (I had to look it up http://en.wikipedia.org/wiki/Fixed-point :-D) but python stores it (correct me if I am wrong) as a float (or double or quad or whatever). If we want to work with fix-point aritmetics we have to invent new functions to do most math. 3) Most "decimal numbers" cannot be stored exactly as floats - that is why b gave the ugly print. But some can, f.x >>> quart = 0.25 >>> quart 0.25 quart translates to a finite "decimal" number in binary (0.01 I think). The point is: representing should-be integers as floats makes you loose precision (negligable probalby but still...). 4) > |> So why not work with int(float * 100) instead? This way you only have > |> to take care of roundoffs etc when dividing. > > And multiplying, and calling most mathematical functions. You are correct of course. My mistake. But, the multiplication is exact before you start rounding off - I wont start counting ordos for int*int vs. float*float, but it could have some advantages >>> a 11122 >>> b 22233 >>> a*b 247275426 >>> (a*b/1,a*b%1) (24727, 5426) On the other hand you will quickly loose accuracy if you perform multiple multiplications or divisions or use other mathematical functions. 5) So, when could this way of thinking be useful? Well, rarely, but if you only add/subtract "decimals" and/or multiply "decimals" with whole numbers or if you want to use some non-metric system to do scientific stuff (compute square feet when having (feet1,inch1) * (feet2,inch2) assuming that inches are atomic.) This could of course be extended to (feet, inch, quarter_of_afoot, sixteeth_of_a_foot) if you'd like - it is all a matter of representation. Regards, Per "It is a gift. A gift to the foes of 'the Terrorists'. Why not use this 'terrorism'? Long has my father, 'George Bush Sr', kept the forces of 'the terrorists' at bay. By the blood of our people are your lands kept safe. Give 'the land of the brave' the weapon of the enemy. Let us use it against him." -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Pascal Costanza schrieb: > (It's really important to understand that the idea is to use this for > deployed programs - albeit hopefully in a more structured fashion - and > not only for debugging. The example I have given is an extreme one that > you would probably not use as such in a "real-world" setting, but it > shows that there is a boundary beyond which static type systems cannot > be used in a meaningful way anymore, at least as far as I can tell.) As soon as the running program can be updated, the distinction between "static" (compile time) and "dynamic" (run time) blurs. You can still erect a definition for such a case, but it needs to refer to the update process, and hence becomes language-specific. In other words, language-independent definitions of dynamic and static typing won't give any meaningful results for such languages. I'd say it makes more sense to talk about what advantages of static vs. dynamic typing can be applied in such a situation. E.g. one interesting topic would be the change in trade-offs: making sure that a type error cannot occur becomes much more difficult (particularly if the set of available types can change during an update), so static typing starts to lose some of its appeal; OTOH a good type system can give you a lot of guarantees even in such a situation, even if it might have to revert to the occasional run-time type check, so static checking still has its merits. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to wrap a whole script in try..except?
Jon Ribbens wrote: In article <[EMAIL PROTECTED]>, Hari Sekhon wrote: I want to wrap a whole script in try ... except. What is the best way of doing this? You could do this maybe: import sys def excepthook(exc_type, exc_value, tb): import modules_needed_to_notify_exception ... sys.excepthook = excepthook import modules_needed_by_script ... I've been trying this out and your method is by far the best I've seen. This is overriding the default exception handler. I don't know the deep magic yet but it works nicely. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Anton van Straaten wrote: > But a program as seen by the programmer has types: the programmer > performs (static) type inference when reasoning about the program, and > debugs those inferences when debugging the program, finally ending up > with a program which has a perfectly good type scheme. It's may be > messy compared to say an HM type scheme, and it's usually not proved to > be perfect, but that again is an orthogonal issue. I like this way of looking at it. -- chris -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Darren New wrote: [me:] > > Personally, I would be quite happy to go there -- I dislike the idea > > that a value has a specific inherent type. > > Interestingly, Ada defines a type as a collection of values. It works > quite well, when one consistantly applies the definition. I have never been very happy with relating type to sets of values (objects, whatever). I'm not saying that it's formally wrong (but see below), but it doesn't fit with my intuitions very well -- most noticeably in that the sets are generally unbounded so you have to ask where the (intentional) definitions come from. Two other notions of what "type" means might be interesting, both come from attempts to create type-inference mechanisms for Smalltalk or related languages. Clearly one can't use the set-of-values approach for these purposes ;-) One approach takes "type" to mean "set of classes" the other takes a finer-grained approach and takes it to mean "set of selectors" (where "selector" is Smalltalk for "name of a method" -- or, more accurately, name of a message). But I would rather leave the question of what a type "is" open, and consider that to be merely part of the type system. For instance the hypothetical nullability analysis type system I mentioned might have only three types NULLABLE, ALWAYSNULL, and NEVERNULL. It's worth noting, too, that (in some sense) the type of an object can change over time[*]. That can be handled readily (if not perfectly) in the informal internal type system(s) which programmers run in their heads (pace the very sensible post by Anton van Straaten today in this thread -- several branches away), but cannot be handled by a type system based on sets-of-values (and is also a counter-example to the idea that "the" dynamic type of an object/value can be identified with its tag). ([*] if the set of operations in which it can legitimately partake changes. That can happen explicitly in Smalltalk (using DNU proxies for instance if the proxied object changes, or even using #becomeA:), but can happen anyway in less "free" languages -- the State Pattern for instance, or even (arguably) in the difference between an empty list and a non-empty list). -- chris -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
David Hopwood wrote: > When people talk > about "types" being associated with values in a "latently typed" or > "dynamically typed" language, they really mean *tag*, not type. I don't think that's true. Maybe /some/ people do confuse the two, but I am certainly a counter-example ;-) The tag (if any) is part of the runtime machinery (or, if not, then I don't understand what you mean by the word), and while that is certainly a reasonably approximation to the type of the object/value, it is only an approximation, and -- what's more -- is only an approximation to the type as yielded by one specific (albeit abstract, maybe even hypothetical) type system. If I send #someMessage to a proxy object which has not had its referent set (and assuming the default value, presumably some variant of nil, does not understand #someMessage), then that's just as much a type error as sending #someMessage to a variable holding a nil value. If I then assign the referent of the proxy to some object which does understand #someMessage, then it is not a type error to send #someMessage to the proxy. So the type has changed, but nothing in the tag system of the language implementation has changed. -- chris -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Chris Smith wrote: > > It would be interesting to see what a language designed specifically to > > support user-defined, pluggable, and perhaps composable, type systems > > would look like. [...] > > You mean in terms of a practical programming language? If not, then > lambda calculus is used in precisely this way for the static sense of > types. Good point. I was actually thinking about what a practical language might look like, but -- hell -- why not start with theory for once ? ;-) > I think Marshall got this one right. The two are accomplishing > different things. In one case (the dynamic case) I am safeguarding > against negative consequences of the program behaving in certain non- > sensical ways. In the other (the static case) I am proving theorems > about the impossibility of this non-sensical behavior ever happening. And so conflating the two notions of type (-checking) as a kind of category error ? If so then I see what you mean, and it's a useful distinction, but am unconvinced that it's /so/ helpful a perspective that I would want to exclude other perspectives which /do/ see the two as more-or-less trivial variants on the same underlying idea. > I acknowledge those questions. I believe they are valid. I don't know > the answers. As an intuitive judgement call, I tend to think that > knowing the correctness of these things is of considerable benefit to > software development, because it means that I don't have as much to > think about at any one point in time. I can validly make more > assumptions about my code and KNOW that they are correct. I don't have > to trace as many things back to their original source in a different > module of code, or hunt down as much documentation. I also, as a > practical matter, get development tools that are more powerful. Agreed that these are all positive benefits of static declarative (more or less) type systems. But then (slightly tongue-in-cheek) shouldn't you be agitating for Java's type system to be stripped out (we hardly /need/ it since the JVM does latent typing anyway), leaving the field free for more powerful or more specialised static analysis ? > (Whether it's possible to create the same for a dynamically typed > language is a potentially interesting discussion; but as a practical > matter, no matter what's possible, I still have better development tools > for Java than for JavaScript when I do my job.) Acknowledged. Contrary-wise, I have better development tools in Smalltalk than I ever expect to have in Java -- in part (only in part) because of the late binding in Smalltalk and it's lack of insistence on declared types from an arbitrarily chosen type system. > On > the other hand, I do like proving theorems, which means I am interested > in type theory; if that type theory relates to programming, then that's > great! That's probably not the thing to say to ensure that my thoughts > are relevant to the software development "industry", but it's > nevertheless the truth. Saying it will probably win you more friends in comp.lang.functional than it looses in comp.lang.java.programmer ;-) -- chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration over recursion?
[Kay Schluehr] > You might use a separate prime generator to produce prime factors. The > factorize algorithm becomes quite simple and configurable by prime > generators. Alas, yours was _so_ simple that it always takes time proportional to the largest prime factor of n (which may be n) instead of worst-case time proportional to sqrt(n). Repair that, and it's not quite so simple anymore. The speed of the sieve generator would also benefit a lot by never looking at even integers, beyond an initial "yield 2" ... the OP said he was looking for speed more than elegance, and they're not good buddies here ;-) > def eratosthenes(): > memo = {} > q = 2 > while True: > p = memo.pop(q, None) > if p is None: > yield q > memo[q*q] = q > else: > x = p + q > while x in memo: > x += p > memo[x] = p > q+=1 > > def factorize(n, sieve = eratosthenes): > if n <= 1: > return [n] > factors = [] > primes = sieve() > for q in primes: > while n % q == 0: > factors.append(q) > n //= q > if n == 1: > return factors At _some_ point you might think that's bound to be faster than only skipping multiples of 2 and 3, because it does fewer divisions. But to get to a particular prime p, the sieve there has to go around its outer loop about 3x as often as the trial() function goes around its inner loop, and grows a dict with about p/ln(p) entries (while the trial() function's memory use is constant), and those aren't free. Applied to 991**2 (constructed so that both functions take time proportional to sqrt(n)), on my box the factorize() function took 4x longer than trial() (approximately 16 seconds versus 4). Trial division isn't practical for such large inputs, but I picked the square of a "large" prime to give factorize() maximum advantage in skipping division attempts (by the time we get to a prime p, factorize() tries about p/ln(p) divisions, while trial() does about p/3; so trial() does about ln(p)/3 times as many divisions as factorize(): the larger the p we need, the larger that _factor_ gets). Alas, it appears that made the dict so big that cache faults on dict accesses more than wiped out the division advantage. At the smaller 83**2, factorize() took only about 3.6x longer, despite losing some of its relative division advantage. In short, it's never what you think it is ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to wrap a whole script in try..except?
Jon Ribbens wrote: In article <[EMAIL PROTECTED]>, Hari Sekhon wrote: I want to wrap a whole script in try ... except. What is the best way of doing this? You could do this maybe: import sys def excepthook(exc_type, exc_value, tb): import modules_needed_to_notify_exception ... sys.excepthook = excepthook import modules_needed_by_script ... having tested this more, I was worried about a recursive call to exception should an exception be raised inside the function but luckily python deals and give you a double traceback. batteries included indeed. Thanks again Hari -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
Another variant, I feel this one more natural as it doesn't contain a C-looking infinite loop (also I made it a generator but this is not the topic). In [160]: def indices(s, subs) : .: last = 0 .: for ind, part in in enumerate(s.split(subs)[:-1]) : .: yield len(part) + last .: last = len(part) + last + len(subs) .: .: In [161]: list(indices('John has a really nice powerbook.', ' ')) Out[161]: [4, 8, 10, 17, 22] In [162]: list(indices('John has a really nice powerbook. John is my friend', 'John')) Out[162]: [0, 34] In [163]: mystring, substr Out[163]: ('John has a really nice powerbook. John is my friend', 'John') In [164]: for i in list(indices(mystring, substr)) : print mystring[i:i+len(substr)] .: John John Actually it's even more efficient than Lundh's one for smaller strings (less than 1000 characters on my box) and slow down as strings go wider (slowly, seems to be a logarithmic progression) due to the split call resulting in creation of a new list. I'd love str implement a xsplit(sub, start, end) method, so I could have wrote : enumerate(s.xsplit(subs, 0, -1)). Le Mercredi 21 Juin 2006 10:28, Nico Grubert a écrit : > Hi there, > > I would like to search for a substring in a string and get the index of > all occurances. > > mystring = 'John has a really nice powerbook.' > substr = ' ' # space > > I would like to get this list: >[4, 8, 10, 17, 22] > > How can I do that without using "for i in mystring" which might be > expensive for large strings? > > Thanks in advance, > Nico -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Re: help() on stdout.closed
On 2006-06-21, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > have you tried things like [...] I have now. I'm not sure what the results are supposed to tell me, but I am not going to press the issue. Suppose I had no idea what sys.stdout.closed was and wanted to find out. Where would I look it up? Pekka -- http://mail.python.org/mailman/listinfo/python-list
Re: help() on stdout.closed
Pekka Karjalainen wrote: > Suppose I had no idea what sys.stdout.closed was and wanted to find out. > Where would I look it up? >>> help(sys.stdout) ... | closed = | True if the file is closed ... in case anyone feels like hacking, support for something like >>> help(sys.stdout, "closed") might be useful, I think. -- http://mail.python.org/mailman/listinfo/python-list
Re: help() on stdout.closed
In <[EMAIL PROTECTED]>, Pekka Karjalainen wrote: > Suppose I had no idea what sys.stdout.closed was and wanted to find out. > Where would I look it up? `sys.stdout` is a file (like) object: http://docs.python.org/lib/bltin-file-objects.html Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration over recursion?
I've been testing my recursive function against your iterative function, and yours is generally a quite steady 50% faster on factorizing 2**n +/- 1 for 0 < n < 60. I think that, for a challenge, I'll try to make a recursive function that matche or beats the iterative function -- it's worth the experiment! Cheers, MTD -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
Maric Michaud wrote: > Another variant, I feel this one more natural as it doesn't contain a > C-looking infinite loop doing things in a convoluted way because you think that non-infinite while- loops are not natural? you can get help for that, you know ;-) > Actually it's even more efficient than Lundh's one for smaller strings (less > than 1000 characters on my box) and slow down as strings go wider (slowly, > seems to be a logarithmic progression) due to the split call resulting in > creation of a new list. and a potentially large number of new strings. there's a lot of string copying going on in there... -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
> So, will y'all just switch from using "dynamically typed" to "latently > typed", and stop talking about any real programs in real programming > languages as being "untyped" or "type-free", unless you really are > talking about situations in which human reasoning doesn't come into > play? I think you'll find it'll help to reason more clearly about this > whole issue. I agree with most of what you say except regarding "untyped". In machine language or most assembly the type of a variable is something held only in the mind of the programmer writing it, and nowhere else. In latently typed languages though the programmer can ask what they type of a particular value is. There is a vast difference to writing code in the latter kind of language to writing code in assembly. I would suggest that at least assembly should be referred to as "untyped". -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
Maric Michaud wrote: > Actually it's even more efficient than Lundh's effbot's solution finds overlapping occurrences, whereas your solution finds non-overlapping occurrences. So efficiency comparisons are not valid. e.g: indices( 'a', 'aa' ) your solution gives: 0,2 effbots's solution: 0,1,2,3 Regards Sreeram signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
urllib2 OpenerDirector question on usage.
Hello all, I am using urllib2 as a part of a web testing tool. One of the things I am testing is the effect of two different people perforing the same actions on the website - do they interfer with each other or not. So to emulate this, I essentially have the following function: def get_opener(): policy = cookielib.DefaultCookiePolicy(rfc2965=True) cj = cookielib.CookieJar(policy) return urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) Now am I right in thinking that since I am creating a separate CookieJar for each opener, then creating two openers and using one for each hypothetical user will achieve this effect - i.e. sessions will be separate from each other in the app, since the openers will return different session cookies back to the server. Cheers, Ant... -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
> I would like to search for a substring in a string and get the index of > all occurances. > > mystring = 'John has a really nice powerbook.' > substr = ' ' # space > > I would like to get this list: >[4, 8, 10, 17, 22] > > How can I do that without using "for i in mystring" which might be > expensive for large strings? >>> mystring = 'John has a really nice powerbook.' >>> substr = ' ' >>> indicies = [i for i in xrange(len(mystring)) if mystring.startswith(substr, i)] >>> indicies [4, 8, 10, 17, 22] is my preferred way of doing this. Theoretically, it doesn't involve copying any bits of the string, as startswith(substring, offset) *should* be smart enough to do the check internally without copying pieces of mystring for comparison, just to return whether a submatch starts there. Whether it *does* do that is another matter for the higher python powers. It also uses xrange which shouldn't create a temporary array of indicies, but rather use an iteratable sequence generator. It should work for finding all 3 instances of "aba' in "abababa" as well, another common query of a similar form here on the list. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Segmentation fault only on Iinux
Unfortunately (i guess), I am not doing any XML. However, I am taking the previous suggestion of putting print lines in every other line of my code and then seeing where it crashes. Hopefully, that will solve the problem. thanks for the suggestions everybody -- Kiran Frank Millman wrote: > Kiran wrote: > > Hello All, > > In my program, I have a main thread which is the GUI (wxPython) and > > then a thread which goes and reads data from a socket. The reason this > > is in a different thread is because the data might take some time to > > come back, and I want to have the GUI to be responsive during this > > wait. > > > > When I run my program in Linux, a segmentation fault occurs. When I > > run it in Windows XP, it works just fine. > > > > Are you doing any xml processing? If so, it may be the same problem as > described in this recent post - > > http://tinyurl.com/l3nr7 > > Frank Millman -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to wrap a whole script in try..except?
Hari Sekhon wrote: Jon Ribbens wrote: In article <[EMAIL PROTECTED]>, Hari Sekhon wrote: I want to wrap a whole script in try ... except. What is the best way of doing this? You could do this maybe: import sys def excepthook(exc_type, exc_value, tb): import modules_needed_to_notify_exception ... sys.excepthook = excepthook import modules_needed_by_script ... having tested this more, I was worried about a recursive call to exception should an exception be raised inside the function but luckily python deals and give you a double traceback. batteries included indeed. Thanks again Hari I see that the exceptionhook is handed 3 things, the name of the error, the explanation, and the traceback object. Does anybody know how I can get the linenumber of the error the way it does normally, since this is very useful info when debugging. I think I need the traceback module but I can't see how to extract the extra info from the traceback object passed to excepthook. -- http://mail.python.org/mailman/listinfo/python-list
very strange bug coercing to Unicode: need string or buffer, int found
i truly didn't understand this error :Traceback (most recent call last): File "D:\Programmation\FrancePaquet\FrancePaquet.py", line 77, in ? cabtri = "zz" + chiffrescabtri + clefcTypeError: coercing to Unicode: need string or buffer, int found >>> if someone could help me i will be glad, this program worked yesterday.RegardsBussierehere is my program :import fileinput,stringdef calculclef(nombre): nombre2 = int(nombre)*10 nombre = str(nombre2) taille = len(nombre) compteur = 0 nombrepair = 0 nombreimpair = 0 compteur = taille - 2 while compteur != -1: print 'nombre :' print nombre[compteur] + '\n' if compteur%2 : nombrepair = nombrepair + int(nombre[compteur]) print 'suite pair %d' % nombrepair else: nombreimpair = nombreimpair + int(nombre[compteur]) print 'suite impair %d' % nombreimpair print compteur = compteur - 1 print nombreimpair print nombrepair clef = nombrepair*3+nombreimpair clef = 10-(clef%10) if clef == 10: clef = 0 return clefcompteclient = "8150"souscompteclient = "03"codeaffranc = "080"partielibre = "142391"print("LES CODES POSTAUX DOIVENT ETRE A LA FIN DU FICHIER CSV ! \n") fichA=raw_input("Entrez le nom du fichier d'entree : ")print ("\n")fichC=raw_input("Entrez le nom du fichier de sortie : ")print ("\n")debutplage = raw_input("Entrez le numero du debut de plage : ") print ("\n")finplage = raw_input("Entrez le numero de fin de plage : ")print ("\n") nbredeplage = int(debutplage) - int(finplage)fiA=open(fichA,"r") fiC=open(fichC,"w")print calculclef(debutplage)compteur = 0debutplagewhile 1: fileencoding = "latin1" ligneA=fiA.readline() ligneA = ligneA.decode(fileencoding) if ligneA == "": break if ligneA != "": stramettre = ligneA if compteur != 0: taille = len(ligneA) codepostal = ligneA[taille-5] + ligneA[taille-4] + ligneA[taille-3] + ligneA[taille-2]+ ligneA[taille-1] print codepostal clefb = calculclef(debutplage) clefb = str(clefb) print clefb num = str(debutplage) cabsuivis = "8w"+ num + clefb stramettre = stramettre + ";*" + cabsuivis + "*" chiffrescabtri = clefb + codepostal + compteclient + souscompteclient + codeaffranc + partielibre clefc = calculclef(chiffrescabtri) cabtri = "zz" + chiffrescabtri + clefc stramettre = stramettre + ";*" + cabtri + "*" fiC.write(stramettre) compteur += 1 print compteur, "\n"print "FINIT"fiA.close()fiC.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Chris Uppal wrote: > > I have never been very happy with relating type to sets of values (objects, > whatever). Indeed, this view is much too narrow. In particular, it cannot explain abstract types, which is *the* central aspect of decent type systems. There were papers observing this as early as 1970. A type system should rather be seen as a logic, stating invariants about a program. This can include operations supported by values of certain types, as well as more advanced properties, e.g. whether something can cause a side-effect, can diverge, can have a deadlock, etc. (There are also theoretic problems with the types-as-sets view, because sufficiently rich type systems can no longer be given direct models in standard set theory. For example, first-class polymorphism would run afoul the axiom of foundation.) > It's worth noting, too, that (in some sense) the type of an object can change > over time[*]. No. Since a type expresses invariants, this is precisely what may *not* happen. If certain properties of an object may change then the type of the object has to reflect that possibility. Otherwise you cannot legitimately call it a type. Taking your example of an uninitialised reference, its type is neither "reference to nil" nor "reference to object that understands message X", it is in fact the union of both (at least). And indeed, languages with slightly more advanced type systems make things like this very explicit (in ML for example you have the option type for that purpose). - Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
Maric Michaud: > I'd love str implement a xsplit(sub, start, end) method, so I could have > wrote : enumerate(s.xsplit(subs, 0, -1)). Some of such str.x-methods (or str.i-methods, etc) can be useful (especially for Py3.0), but keeping APIs simple and compact is very important, otherwise when you program you have to waste some time looking things up in the manuals. Such lists of methods are a compromise between (among other things) completeness and compactness. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Joachim Durchholz wrote: > Pascal Costanza schrieb: >> (It's really important to understand that the idea is to use this for >> deployed programs - albeit hopefully in a more structured fashion - >> and not only for debugging. The example I have given is an extreme one >> that you would probably not use as such in a "real-world" setting, but >> it shows that there is a boundary beyond which static type systems >> cannot be used in a meaningful way anymore, at least as far as I can >> tell.) > > As soon as the running program can be updated, the distinction between > "static" (compile time) and "dynamic" (run time) blurs. > You can still erect a definition for such a case, but it needs to refer > to the update process, and hence becomes language-specific. In other > words, language-independent definitions of dynamic and static typing > won't give any meaningful results for such languages. > > I'd say it makes more sense to talk about what advantages of static vs. > dynamic typing can be applied in such a situation. > E.g. one interesting topic would be the change in trade-offs: making > sure that a type error cannot occur becomes much more difficult > (particularly if the set of available types can change during an > update), so static typing starts to lose some of its appeal; OTOH a good > type system can give you a lot of guarantees even in such a situation, > even if it might have to revert to the occasional run-time type check, > so static checking still has its merits. I am not opposed to this view. The two examples I have given for things that are impossible in static vs. dynamic type systems were intentionally extreme to make the point that you have to make a choice, that you cannot just blindly throw (instances of) both approaches together. Static type systems potentially change the semantics of a language in ways that cannot be captured by dynamically typed languages anymore, and vice versa. There is, of course, room for research on performing static type checks in a running system, for example immediately after or before a software update is applied, or maybe even on separate type checking on software increments such that guarantees for their composition can be derived. However, I am not aware of a lot of work in that area, maybe because the static typing community is too focused on compile-time issues. Personally, I also don't think that's the most interesting issue in that area, but that's of course only a subjective opinion. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
Le Mercredi 21 Juin 2006 14:01, Fredrik Lundh a écrit : > > Another variant, I feel this one more natural as it doesn't contain a > > C-looking infinite loop > > doing things in a convoluted way because you think that non-infinite while- > loops are not natural? you can get help for that, you know ;-) Hehe, I was looking for a more pythonic solution (one like Tim gave), but not convinced. Sure these loops are common and natural. They're so natural I wonder why I avoid this kind of code : for i in lst : ... if continue_condition : continue ... if break_condition : break ... Maybe I'll vote for a goto statment for Python3000... Really I prefer code like this, when it's possible : for i in [ e for e in lst[:first_breaking_elt] if not e in continue_condition ] : > and a potentially large number of new strings. there's a lot of string > copying going on in there... Oh, yes, you're right, a xsplit operator would be of minor help as it will copy all the string piece by piece. Le Mercredi 21 Juin 2006 14:27, K.S.Sreeram a écrit : > > Actually it's even more efficient than Lundh's > > effbot's solution finds overlapping occurrences, whereas your solution > finds non-overlapping occurrences. Missed that. > So efficiency comparisons are not valid. Right, but anyway, the problem is more about memory usage. Regards, -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Delivery reports about your e-mail
-This message contained a computer virus which has been detected and deleted by the BT Business Email Virus Filter to avoid infecting your computer. - -You may wish to contact the sender of this email requesting they remove any virus infection from their PC before re-sending the email and attachment to you, virus-free. - -Attachment: text.scr -Problem: virus infected W32/MyDoom-O -Action taken: deleted - -Any original message will appear as an attachment; if this is blank or absent no text was supplied.The original message was received at Wed, 21 Jun 2006 14:12:13 +0100 from iee.org.uk [71.231.246.114] - The following addresses had permanent fatal errors - VIRUS WARNING Message (from c2bthomr09.btconnect.com) The virus W32/MyDoom-O was detected in email attachment [2.2] text.scr. The infected attachment has been deleted. -- http://mail.python.org/mailman/listinfo/python-list
Re: need all python dialog equivalent
[EMAIL PROTECTED] wrote: > dialog binary is 110 KB. Won't it fit ? missing library. I have ncurses and newt and dialog seems to require something called ncursesw. I've been trying to find the Python newt module as well and that seems to be as invisible as the creature it's named after. -- http://mail.python.org/mailman/listinfo/python-list
How to override the doc of an object instance.
Hi, I'm not really sure about the right terminology, but here is my question, boiled down to this code: class widget (object): """This is a widget.""" def __init__(self): self._x = None def fget(self): return self._x def fset(self, value): self._x = value print self._x, 'Ok' x = property(fget = fget, fset = fset, doc= "It prints") print widget.x.__doc__ w = widget() w.x = 5 print w.x.__doc__ I would like the last statement to print the doc string that I specified in property, instead of the docstring for an int. The goal is to have ipython print that string with the command w.x? So the user knows what this attribute does, and how he can set it. Is this possible ? Thanks, David Huard -- http://mail.python.org/mailman/listinfo/python-list
Re: need all python dialog equivalent
Miki wrote: > Hello Eric, > >> Is there anything like an all Python dialog equivalent floating around? > http://www.pythonware.com/library/tkinter/introduction/ I'm sorry. I should have been more explicit. I need a textbased interface such as the ones you would get with curses and dialogue. ---eric -- http://mail.python.org/mailman/listinfo/python-list
Re: very strange bug coercing to Unicode: need string or buffer, int found
"bussiere maillist" <[EMAIL PROTECTED]> wrote: > --=_Part_118629_1441854.1150895040355 > i truly didn't understand this error : > Traceback (most recent call last): > File "D:\Programmation\FrancePaquet\FrancePaquet.py", line 77, > in ? > cabtri = "zz" + chiffrescabtri + clefc > TypeError: coercing to Unicode: need string or buffer, int found > > def calculclef(nombre): > if clef == 10: > clef = 0 > return clef > > clefb = calculclef(debutplage) > clefb = str(clefb) > print clefb > clefc = calculclef(chiffrescabtri) > cabtri = "zz" + chiffrescabtri + clefc Your calculclef function returns an integer. You explitly convert clefb into a string, but you never convert clefc into a string, hence the TypeError. max -- http://mail.python.org/mailman/listinfo/python-list
Re: OS specific command in Python
I have a question on getpass. Since I am a newbie you might find it a little dumb. By using the getpass, are u trying to retrieve the username and password of remote mahcine or local ? Avell Diroll wrote: > [EMAIL PROTECTED] wrote: > > When you connect (via ssh or telnet) to a remote machine, you need to > > type (manually) > > your username and your password. Programming that is never easy. > > > > This is really eased by the module getpass (std library) : > > ### > > import getpass > > login = getpass.getuser() > password = getpass.getpass() > > ### > > If the username is different from your system login this can be changed to : > > ### > > import getpass > > login = raw_input('login: ') > password = getpass.getpass() > > ### > > > Python definitely comes with batteries included ! -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
K.S.Sreeram wrote: > effbot's solution finds overlapping occurrences, whereas your solution > finds non-overlapping occurrences. So efficiency comparisons are not valid. oops. my bad. here's a fixed version: result = []; pos = 0 try: while 1: pos = mystring.index(substr, pos) result.append(pos) pos += len(substr) except ValueError: pass # done or, if you prefer the generator variant: def finditer(string, substr): pos = 0 index = string.index try: while 1: pos = index(substr, pos) yield pos pos += len(substr) except ValueError: pass # done -- http://mail.python.org/mailman/listinfo/python-list
Re: How to override the doc of an object instance.
Le Mercredi 21 Juin 2006 06:50, David Huard a écrit : > class widget (object): > """This is a widget.""" > def __init__(self): > self._x = None > def fget(self): > return self._x > def fset(self, value): > self._x = value > print self._x, 'Ok' > x = property(fget = fget, fset = fset, doc= "It prints") > > > print widget.x.__doc__ > > w = widget() > w.x = 5 > print w.x.__doc__ This is w.__class__.x.__doc__. w.x return the value you put in self._x, say an int, so w.x.__doc__ will print the docstring of int. -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
"Rob Thorpe" <[EMAIL PROTECTED]> writes: > Matthias Blume wrote: >> "Rob Thorpe" <[EMAIL PROTECTED]> writes: >> >> > I think we're discussing this at cross-purposes. In a language like C >> > or another statically typed language there is no information passed >> > with values indicating their type. >> >> You seem to be confusing "does not have a type" with "no type >> information is passed at runtime". >> >> > Have a look in a C compiler if you don't believe me. >> >> Believe me, I have. > > In a C compiler the compiler has no idea what the values are in the > program. It is no different from any other compiler, really. If the compiler sees the literal 1 in a context that demands type int, then it knows perfectly well what value that is. > It knows only their type in that it knows the type of the variable they > are contained within. > Would you agree with that? > >> > No it doesn't. Casting reinterprets a value of one type as a value of >> > another type. >> > There is a difference. If I cast an unsigned integer 20 to a >> > signed integer in C on the machine I'm using then the result I will get >> > will not make any sense. >> >> Which result are you getting? What does it mean to "make sense"? > > Well the right one actually, bad example. > > But, if I cast an unsigned int 25 to signed I get -1794967296. So, why do you think this "does not make sense"? And, as this example illustrates, casting in C maps values to values. Depending on the types of the source and the target, a cast might change the underlying representation, or it might leave it the same. But it does produce a value, and the result value is usually not the same as the argument value, even if the representation is the same. Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: OS specific command in Python
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote: >> So basically, instead of typing in on the command line argument I want >> to have it in a python program and let it do the action. > > Try exec() and execfile() from the standard library (IIRC) Ths os.spawn...() functions are likely to be better suited to what he wants to do. >> ssh [EMAIL PROTECTED] .etc > > When you connect (via ssh or telnet) to a remote machine, you need to > type (manually) your username and your password. Programming that is > never easy. Indeed, so it is much easier to use public-key authentication with an unencrypted private key, that way you don't have to type any passwords. See the "AUTHORIZED_KEYS FILE FORMAT" section of the 'sshd' man page, and the 'ssh-keygen' command. -- http://mail.python.org/mailman/listinfo/python-list
Re: very strange bug coercing to Unicode: need string or buffer, int found
"bussiere maillist" wrote: >i truly didn't understand this error : > Traceback (most recent call last): > File "D:\Programmation\FrancePaquet\FrancePaquet.py", line 77, in ? >cabtri = "zz" + chiffrescabtri + clefc > TypeError: coercing to Unicode: need string or buffer, int found hint: >>> "one" + u"two" + 3 Traceback (most recent call last): File "", line 1, in ? TypeError: coercing to Unicode: need string or buffer, int found -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Joachim Durchholz <[EMAIL PROTECTED]> writes: > Matthias Blume schrieb: >> Joachim Durchholz <[EMAIL PROTECTED]> writes: >> >>> Matthias Blume schrieb: Perhaps better: A language is statically typed if its definition includes (or ever better: is based on) a static type system, i.e., a static semantics with typing judgments derivable by typing rules. Usually typing judgmets associate program phrases ("expressions") with types given a typing environment. >>> This is defining a single term ("statically typed") using three >>> undefined terms ("typing judgements", "typing rules", "typing >>> environment"). >> This was not meant to be a rigorous definition. > > Rigorous or not, introducing additional undefined terms doesn't help > with explaining a term. I think you missed my point. My point was that a language is statically typed IF IT IS DEFINED THAT WAY, i.e., if it has a static type system that is PART OF THE LANGUAGE DEFINITION. The details are up to each individual definition. >> Also, I'm not going to repeat the textbook definitions for those >> three standard terms here. > > These terms certainly aren't standard for Perl, Python, Java, or Lisp, Indeed. That's because these languages are not statically typed. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to override the doc of an object instance.
On Wed, 21 Jun 2006 15:39:02 +0200, Maric Michaud wrote: > This is w.__class__.x.__doc__. Thanks, So in order to implement what I want, I should rather consider an ipython hack to print w.__class__.x.__doc__ when it exists, instead of w.x.__doc_ ? Does this makes sense or it will ruin the standard behaviour? David -- http://mail.python.org/mailman/listinfo/python-list
Re: need all python dialog equivalent
On 2006-06-21, Eric S. Johansson <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: >> dialog binary is 110 KB. Won't it fit ? > > missing library. I have ncurses and newt and dialog seems to require > something called ncursesw. I've been trying to find the Python newt > module as well and that seems to be as invisible as the creature it's > named after. The most recent version of newt I've got is at ftp://ftp.visi.com/users/grante/stuff/newt-0.50.tar.gz The python module is called "snack" -- Grant Edwards grante Yow! Yow! Am I cleansed at yet?! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Psyco performance
> > > Place all the code in a function. Even without psyco you might get > > > somewhat better performances then. And I doubt psyco can optimise code > > > that isn't in a function anyway. Another thing I wasn't considering is that the first call with psyco enabled might be slower. The 2nd time the psyco-compiled function is called is where the speed improvement may be present. With the code at the bottom, I get these results: without psyco = 0.000421282593179 first call with psyco = 0.000902349320933 with psyco = 5.30793718196e-005 first call with psyco = 114.190981432 % slower 2nd call with psyco = 87.400530504 % faster import time import psyco def test(l): result = 0 for item in l: result += item return result l = list(range(0, 1000)) t1 = time.clock() l2 = test(l) t2 = time.clock() no_psyco = t2 - t1 psyco.log() psyco.bind(test) t1 = time.clock() l2 = test(l) t2 = time.clock() first_call_with_psyco = t2 - t1 t1 = time.clock() l2 = test(l) t2 = time.clock() with_psyco = t2 - t1 print 'without psyco = ',no_psyco print 'first call with psyco = ',first_call_with_psyco print 'with psyco = ',with_psyco first_delta = ((no_psyco - first_call_with_psyco)/no_psyco) * 100 delta = ((no_psyco - with_psyco)/no_psyco) * 100 if(first_delta > 0): result = 'faster' else: result = 'slower' print 'first call with psyco = ',abs(first_delta),'% ',result if(delta > 0): result = 'faster' else: result = 'slower' print '2nd call with psyco = ',abs(delta),'% ',result -- http://mail.python.org/mailman/listinfo/python-list
Re: OS specific command in Python
Hi Avell, I want to communicate using subprocess module but my task is a little different. May be you can guide me. I have a linux box, from where I remotely execute all the commands. The remote machine is windows machine. I installed an OpenSSH server for windows to send the shutdown command. I setup the public keys in such a way that I could login to SSH server without using password. I used import os os.system('ssh [EMAIL PROTECTED] shutdown -s') I was wondering how can I interact with an application . Since you mentioned about subprocess module, I want a ability that my PYthon script can actually interact with the windows box and launch and close application there remotely. Any suggestions on how to do this ? Every help is appreciated. Thanks for your time Avell Diroll wrote: > This is an simple way to proceed if you don't need your python script to > know what happens to the launched process ... > When you need to : > * send some input to the command from the python script after it is launched > * get the output of the command in your python script > * get the pid associated to your command > * wait for your command to finish > * pipe some shell commands > * ... > you should use the subprocess module. > > Here is a quick example from the Python Reference Library : > http://docs.python.org/lib/node242.html > > ##Shell Script : > output=`dmesg | grep hda` > > > ##Python Script : > from subprocess import Popen > p1 = Popen(["dmesg"], stdout=PIPE) > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > output = p2.communicate()[0] -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Chris Uppal schrieb: > Chris Smith wrote: >> I think Marshall got this one right. The two are accomplishing >> different things. In one case (the dynamic case) I am safeguarding >> against negative consequences of the program behaving in certain non- >> sensical ways. In the other (the static case) I am proving theorems >> about the impossibility of this non-sensical behavior ever happening. > > And so conflating the two notions of type (-checking) as a kind of category > error ? If so then I see what you mean, and it's a useful distinction, but am > unconvinced that it's /so/ helpful a perspective that I would want to exclude > other perspectives which /do/ see the two as more-or-less trivial variants on > the same underlying idea. It is indeed helpful. Just think of all the unit tests that you don't have to write. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Matthias Blume schrieb: > Joachim Durchholz <[EMAIL PROTECTED]> writes: > >> Matthias Blume schrieb: >>> Joachim Durchholz <[EMAIL PROTECTED]> writes: >>> Matthias Blume schrieb: > Perhaps better: A language is statically typed if its definition > includes (or ever better: is based on) a static type system, i.e., a > static semantics with typing judgments derivable by typing rules. > Usually typing judgmets associate program phrases ("expressions") with > types given a typing environment. This is defining a single term ("statically typed") using three undefined terms ("typing judgements", "typing rules", "typing environment"). >>> This was not meant to be a rigorous definition. >> Rigorous or not, introducing additional undefined terms doesn't help >> with explaining a term. > > I think you missed my point. My point was that a language is > statically typed IF IT IS DEFINED THAT WAY, i.e., if it has a static > type system that is PART OF THE LANGUAGE DEFINITION. The details are > up to each individual definition. Well, that certainly makes more sense to me. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Matthias Blume wrote: > "Rob Thorpe" <[EMAIL PROTECTED]> writes: > > Matthias Blume wrote: > >> "Rob Thorpe" <[EMAIL PROTECTED]> writes: > >> > >> > I think we're discussing this at cross-purposes. In a language like C > >> > or another statically typed language there is no information passed > >> > with values indicating their type. > >> > >> You seem to be confusing "does not have a type" with "no type > >> information is passed at runtime". > >> > >> > Have a look in a C compiler if you don't believe me. > >> > >> Believe me, I have. > > > > In a C compiler the compiler has no idea what the values are in the > > program. > > It is no different from any other compiler, really. If the compiler > sees the literal 1 in a context that demands type int, then it knows > perfectly well what value that is. Well, with a literal yes. But with the value of some variable x at runtime it only know the type because it knows the type of the variable. Similarly the type of values generated by an expression are only known because the type the expression generates is known. > > It knows only their type in that it knows the type of the variable they > > are contained within. > > Would you agree with that? Would you? > >> > No it doesn't. Casting reinterprets a value of one type as a value of > >> > another type. > >> > There is a difference. If I cast an unsigned integer 20 to a > >> > signed integer in C on the machine I'm using then the result I will get > >> > will not make any sense. > >> > >> Which result are you getting? What does it mean to "make sense"? > > > > Well the right one actually, bad example. > > > > But, if I cast an unsigned int 25 to signed I get -1794967296. > > So, why do you think this "does not make sense"? Well, it makes sense in terms of the C spec certainly. It does not make sense in that it does not emit an error. >And, as this example > illustrates, casting in C maps values to values. Depending on the > types of the source and the target, a cast might change the underlying > representation, or it might leave it the same. But it does produce a > value, and the result value is usually not the same as the argument > value, even if the representation is the same. Yes. I'm not arguing with that. -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] code is data
Bruno Desthuilliers wrote: > You mean like 'converting' javascript to python or python to ruby (or > converting any home-grown DSL to Python, etc) ? Yes, but also what some other posters mentioned, making Pythons internal parsing tree available to other programs (and to Python itself) by using a widely used standard like XML as its datatype. >> Then there are some people who keep insisting they don't understand what >> I'm talking about until I simplify things enough to get them on-board, > > count me in then :( Sorry about that. >> but then simply dismiss my ideas with 'you can already do that easily >> with this standard python construct'. This strategy was also eloquently >> refuted by some other poster, so I don't need to repeat it :-) >> >> I've gotten a lot of things to think about, so thanks all for your >> thoughts, but since this is getting way above my head I'll just wimp out >> and leave the rest of the thread to the experts! > > No way you will escape from your responsabilities so easily !-) Ok, count me back in then too :-) Of course I will be available for further discussion. If more than ten people demand a PEP and no better champion is available (very unlikely) I'll even write a proposal. Anton -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Pascal Costanza schrieb: > Static type systems potentially change the semantics of a > language in ways that cannot be captured by dynamically typed languages > anymore, and vice versa. Very true. I also suspect that's also why adding type inference to a dynamically-typed language doesn't give you all the benefits of static typing: the added-on type system is (usually) too weak to express really interesting guarantees, usually because the language's semantics isn't tailored towards making the inference steps easy enough. Conversely, I suspect that adding dynamic typing to statically-typed languages tends to miss the most interesting applications, mostly because all the features that can "simply be done" in a dynamically-typed language have to be retrofitted to the statically-typed language on a case-by-case basis. In both cases, the language designers often don't know the facilities of the opposed camp well enough to really assess the trade-offs they are doing. > There is, of course, room for research on performing static type checks > in a running system, for example immediately after or before a software > update is applied, or maybe even on separate type checking on software > increments such that guarantees for their composition can be derived. > However, I am not aware of a lot of work in that area, maybe because the > static typing community is too focused on compile-time issues. I think it's mostly because it's intimidating. The core semantics of an ideal language fits on a single sheet of paper, to facilitate proofs of language properties. Type checking dynamically-loaded code probably wouldn't fit on that sheet of paper. (The non-core semantics is then usually a set of transformation rules that map the constructs that the programmer sees to constructs of the core language.) Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Remote Boot Manager Scripting (Python)
I just started to write a small project in Python. I was wondering if there can be something like remote boot manager. I have to remotely start a computer. It has dual boot (WinXP and Linux). My remote computer is Linux which will send command to remotely boot the other computer. Can we write python script or some utility which would let us select the Operating System to boot ? For example If we send parameter "WIN" it boots into Windows and if we send "NIX" it boots into Linux. Every help is appreciated. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: new python icons for windows
Istvan Albert wrote: > But these new icons are too large, too blocky and too pastel. Hooray! Glad to see *someone* doesn't like 'em, I'll expect a few more when b1 hits. :-) Although I can't really see 'large', 'blocky' or 'pastel'... they're the same size and shape as other Windows document icons, and I personally find the Python logo colours quite striking. If it's the new-fangled shadey gradienty kind of nonsense you don't like, you could also try the low-colour versions. eg. ICOs compiled with only 16-colour and 16/32 sizes: http://doxdesk.com/file/software/py/pyicons-tiny.zip > For example it resembles the icon for text files. This is intentional: to make it obvious that .py files are the readable, editable scripts, contrasting with .pyc's binary gunk - something that wasn't 100% clear before. With the obviousness of the Python-plus and the strong difference between the white and black base document icons, squinting shouldn't really be necessary IMO. > can someone point me to a page/link that contains the old icons? Sure, http://svn.python.org/view/python/branches/release24-maint/PC/py.ico http://svn.python.org/view/python/branches/release24-maint/PC/pyc.ico http://svn.python.org/view/python/branches/release24-maint/PC/pycon.ico -- And Clover mailto:[EMAIL PROTECTED] http://www.doxdesk.com/ -- http://mail.python.org/mailman/listinfo/python-list
returning index of minimum in a list of lists
Hi all, Is there a simple python function to return the list index of the minimum entry in a list of lists? ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. Or, same question but just for a list of numbers, not a list of lists. Thanks, Josh -- http://mail.python.org/mailman/listinfo/python-list
Re: How to override the doc of an object instance.
"David Huard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On Wed, 21 Jun 2006 15:39:02 +0200, Maric Michaud wrote: > > > This is w.__class__.x.__doc__. > > Thanks, > > So in order to implement what I want, I should rather consider an > ipython hack to print w.__class__.x.__doc__ when it exists, instead of > w.x.__doc_ ? Does this makes sense or it will ruin the standard behaviour? > > David > No need to, just assign your special docstrings to w.x.__doc__, and print w.x.__doc__. Instances that have special docstrings will print their instance-specific versions; instances without instance-specific docstrings will print the class-level version. See below. -- Paul >>> class W(object): ... "Class-level docstring for W" ... pass ... >>> z = W() >>> z.__doc__ 'Class-level docstring for W' >>> z.__doc__ = "instance-level docstring, just for z" >>> z.__doc__ 'instance-level docstring, just for z' >>> zz = W() >>> print zz.__doc__ Class-level docstring for W >>> print z.__doc__ instance-level docstring, just for z -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
Tim Chase wrote: > >>> indicies = [i for i in xrange(len(mystring)) if > mystring.startswith(substr, i)] > >>> indicies > [4, 8, 10, 17, 22] > > is my preferred way of doing this. it's things like this that makes me wonder why I spent a week speeding up the string implementation for Python 2.5 (with special emphasis on find/index-related performance)... -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Chris Smith wrote: > > When I used the word "type" above, I was adopting the > working definition of a type from the dynamic sense. That is, I'm > considering whether statically typed languages may be considered to also > have dynamic types, and it's pretty clear to me that they do. I suppose this statement has to be evaluated on the basis of a definition of "dynamic types." I don't have a firm definition for that term, but my working model is runtime type tags. In which case, I would say that among statically typed languages, Java does have dynamic types, but C does not. C++ is somewhere in the middle. Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Joachim Durchholz wrote: > > Hmm... I think this distinction doesn't cover all cases. > > Assume a language that > a) defines that a program is "type-correct" iff HM inference establishes > that there are no type errors > b) compiles a type-incorrect program anyway, with an establishes > rigorous semantics for such programs (e.g. by throwing exceptions as > appropriate). > The compiler might actually refuse to compile type-incorrect programs, > depending on compiler flags and/or declarations in the code. > > Typed ("strongly typed") it is, but is it statically typed or > dynamically typed? I think what this highlights is the fact that our existing terminology is not up to the task of representing all the possible design choices we could make. Some parts of dynamic vs. static a mutually exclusive; some parts are orthogonal. Maybe we have reached the point where trying to cram everything in two one of two possible ways of doing things isn't going to cut it any more. Could it be that the US two-party system has influenced our thinking? Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: need all python dialog equivalent
Eric S. Johansson wrote: > I'm creating a dialogue style interface for an application on a > dedicated system. All I have is basic Python 2.3. Is there anything > like an all Python dialog equivalent floating around? I'm currently > hacking away in curses but it's taking me a long way down what I fear to > be a wrong path. http://excess.org/urwid/ ? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
"Rob Thorpe" <[EMAIL PROTECTED]> writes: >> >> > No it doesn't. Casting reinterprets a value of one type as a value of >> >> > another type. >> >> > There is a difference. If I cast an unsigned integer 20 to a >> >> > signed integer in C on the machine I'm using then the result I will get >> >> > will not make any sense. >> >> >> >> Which result are you getting? What does it mean to "make sense"? >> > >> > Well the right one actually, bad example. >> > >> > But, if I cast an unsigned int 25 to signed I get -1794967296. >> >> So, why do you think this "does not make sense"? > > Well, it makes sense in terms of the C spec certainly. > It does not make sense in that it does not emit an error. Why not? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Rob Thorpe wrote: > Matthias Blume wrote: >>"Rob Thorpe" <[EMAIL PROTECTED]> writes: >> >>>I think we're discussing this at cross-purposes. In a language like C >>>or another statically typed language there is no information passed >>>with values indicating their type. >> >>You seem to be confusing "does not have a type" with "no type >>information is passed at runtime". >> >>>Have a look in a C compiler if you don't believe me. >> >>Believe me, I have. > > In a C compiler the compiler has no idea what the values are in the program. > It knows only their type in that it knows the type of the variable they > are contained within. > Would you agree with that? No. In any language, it may be possible to statically infer that the value of an expression will belong to a set of values smaller than that allowed by the expression's type in that language's type system. For example, all constants have a known value, but most constants have a type which allows more than one value. (This is an essential point, not just nitpicking.) -- David Hopwood <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
Joachim Durchholz wrote: > > On a semantic level, the tag is always there - it's the type (and > definitely part of an axiomatic definition of the language). > Tag elimination is "just" an optimization. I see what you're saying, but the distinction is a bit fine for me. If the language has no possible mechanism to observe the it-was-only-eliminated-as-an-optimization tag, in what sense is it "always there?" E.g. The 'C' programming language. Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: What is Expressiveness in a Computer Language
David Hopwood wrote: > > Oh, but it *does* make sense to talk about dynamic tagging in a statically > typed language. > > That's part of what makes the term "dynamically typed" harmful: it implies > a dichotomy between "dynamically typed" and "statically typed" languages, > when in fact dynamic tagging and static typing are (mostly) independent > features. That's really coming home to me in this thread: the terminology is *so* bad. I have noticed this previously in the differences between structural and nominal typing; many typing issues associated with this distinction are falsely labeled as a static-vs-dynamic issues, since so many statically type languages are nominally typed. We need entirely new, finer grained terminology. Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: How to override the doc of an object instance.
Le Mercredi 21 Juin 2006 15:58, David Huard a écrit : > On Wed, 21 Jun 2006 15:39:02 +0200, Maric Michaud wrote: > > This is w.__class__.x.__doc__. > > Thanks, > > So in order to implement what I want, I should rather consider an > ipython hack to print w.__class__.x.__doc__ when it exists, instead of > w.x.__doc_ ? Does this makes sense or it will ruin the standard behaviour? > You can replace __IPYTHON__.magic_pinfo at startup to honor properies, but the help command is already more explicit, try : In [53]: class a(object) : : x=property(lambda s: 0, doc='my doc string') : : In [54]: b=a() In [55]: help(b) Also you can do something like that (put it in some startup script) : In [27]: __IPYTHON__.old_pinfo = __IPYTHON__.magic_pinfo In [28]: def new_pinfo(obj) : : return __IPYTHON__.old_pinfo('modified_version_of_obj') : In [29]: __IPYTHON__.magic_pinfo = new_pinfo But you can also send a bug report to Ipython maintainer :) > David -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list