Re: Suggestion: str.itersplit()
On Apr 21, 8:58 am, Dustan <[EMAIL PROTECTED]> wrote: > >From my searches here, there is no equivalent to java's > > StringTokenizer in python, which seems like a real shame to me. > > However, str.split() works just as well, except for the fact that it > creates it all at one go. I suggest an itersplit be introduced for > lazy evaluation, if you don't want to take up recourses, and it could > be used just like java's StringTokenizer. > > Comments? That would be good, because then you could iterate over strings the same way that you iterate over files: for line in string.itersplit("\n"): ## for block ## -- http://mail.python.org/mailman/listinfo/python-list
Re: Significance of "start" parameter to string method "endswith"
On Apr 19, 3:58 pm, Boris Dušek <[EMAIL PROTECTED]> wrote: > Hello, > > what is the use-case of parameter "start" in string's "endswith" > method? Consider the following minimal example: > > a = "testing" > suffix="ing" > a.endswith(suffix, 2) > > Significance of "end" is obvious. But not so for "start". > > Let's assume the "end" parameter is not used - then the function > should simple check that the last "len(suffix)" characters of "a" are > equal to "ing", no matter where we start (the function does not *scan* > the string from the "start", does it?) > Only case where it would make difference is if we had start + > len(suffix) < len(a) (excuse possible "of-by-one" error :-) > Then the function would never return True. But is there a real use > case when we would test for endswith like this? (knowing that it must > return false?) > > Thanks for any ideas/experience. > Boris Basically, this must be so in order for this to be Pythonic. This is because it is an object oriented language, and functions can be passed as arguments. Say, for example, you have the following function: def foo(function,instance,param): if function(instance,param,2,4): return True else: return False The function must work whether you pass it foo(str.endswith,"blaahh","ahh"), or foo(str.startswith,"blaahh","aah"). This is a really bad example, but it gets the point across that similar functions must have similar parameters in order to be Pythonic. I personally have never used the second or third parameters in this function nor in str.startswith. -- http://mail.python.org/mailman/listinfo/python-list
Re: working of round()
On Apr 15, 8:06 pm, [EMAIL PROTECTED] wrote: > Does round() always perfectly return the output expected or are there > some artifacts which don't allow perfect functionality > > Using python 2.5: > > >>> round(12.234, 2) > 12.23 > >>> round(12.234, 3) > 12.234 > >>> round(12.234, 1) > 12.199 > > but was expecting 12.2 > > Also, for round(x,n), can't 'x' be an expression > > round(5.25/2, 2) > > was expecting 2.62 , but > > >>> round(5.25/2, 2) > > 2.6299 The problem is that floats are encoded as fractions where the denominator is an exponent of 2. 2.63 is not representable as such a fraction. 2.6299... is the closest fraction. Rounding this number will only give you the same thing. If you want decimals to act as expected, use the Decimal class in module decimal. It works as expected, but is much slower. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Web Servers and Page Retrievers
And yes, I do have two email addresses that I use for Python-List On 4/11/07, Collin Stocks <[EMAIL PROTECTED]> wrote: I tried it, and when checking it using a proxy, saw that it didn't really work, at least in the version that I have (urllib v1.17 and urllib2 v2.5). It just added that header onto the end, therefore making there two User-Agent headers, each with different values. I might add that my script IS able to retrieve search pages from Google, whereas both urllibs are FORBIDDEN with the headers that they use. On 4/8/07, Max Erickson <[EMAIL PROTECTED]> wrote: > > Subscriber123 <[EMAIL PROTECTED]> wrote: > > urllib, or urllib2 for advanced users. For example, you can > > easily set your own headers when retrieving and serving pages, > > such as the User-Agent header which you cannot set in either > > urllib or urllib2. > > Sure you can. See: > > http://www.diveintopython.org/http_web_services/user_agent.html > > (though the behavior was changed for python 2.3 to make setting the > user agent work better) > > > max > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Python Web Servers and Page Retrievers
I wrote most of the following script, useful for retrieving pages from the web and serving web pages. Since it is so low level, it is much more customizable than simpleHTTPserver, cgiHTTPserver, urllib, or urllib2 for advanced users. For example, you can easily set your own headers when retrieving and serving pages, such as the User-Agent header which you cannot set in either urllib or urllib2. (sorry for not putting in any comments!) By the way, I just threw this together quickly, and haven't really had time to test retrieve() very much. Please let me know if it is buggy. I guess I should also write a dictToQuery() function. Oh well. import socket host,port='',80 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) sock.bind((host,port)) sock.listen(1) def serve(function=lambda *args:(args[2],200,'OK',{},'')): """\ def serve(function(method,filename,httpversion,headers,get,post)) Serves one request, calling function() with the above parameters. function() must return (httpversion,code, accepted,headers,content) in that order. If you don't pass a function, then function=lambda *args:(args[2],200,'OK',{},'') """ csock,caddr=sock.accept() rfile=csock.makefile('r',0) wfile=csock.makefile('w',0) # Protocol exchange - read request headers={} line=rfile.readline().strip() split1=line.find(' ') method,remainder=line[:split1].strip(),line[split1+1:].strip() split2=remainder.find(' ') filename,httpversion=remainder[:split2].strip(),remainder[split2+1:].strip() while 1: line=rfile.readline().strip() print line if line=='': break else: split=line.find(':') key,value=line[:split],line[split+1:] headers[key.strip()]=value.strip() try: post=rfile.read(int(headers['Content-Length'])) except: post='' get=queryToDict(filename) post=queryToDict(post) loc=filename.find("?") if loc>-1: filename=filename[:loc] print "get:",`get` print "post:",`post` httpversion,code,accepted,headers,content=function(method,filename,httpversion,headers,get,post) wfile.write("%s %s %s\n"%(httpversion,code,accepted)) for header in list(headers): wfile.write("%s: %s\n"%(header,headers[header])) wfile.write("\n%s\n"%content) wfile.close() csock.close() def retrieve(host,port=80,method='GET',filename='/',httpversion='HTTP/1.0',headers={},post=''): """\ Retrieves one web page from: http://host:port/filename with the headers """ sock.connect((host,port)) rfile=sock.makefile('r',0) wfile=sock.makefile('w',0) wfile.write("%s %s %s\n"%(method,filename,httpversion)) for header in list(headers): wfile.write("%s: %s\n"%(header,headers[header])) wfile.write('\n') wfile.write("%s\n"%post) headers={} line=rfile.readline().strip() split1=line.find(' ') httpversion,remainder=line[:split1].strip(),line[split1+1:].strip() split2=remainder.find(' ') code,accepted=remainder[:split2].strip(),remainder[split2+1:].strip() while 1: line=rfile.readline().strip() if line=='': break else: split=line.find(':') key,value=line[:split],line[split+1:] headers[key.strip()]=value.strip() return httpversion,code,accepted,headers,rfile def queryToDict(query): if '?' in query: query=query[query.index('?')+1:] kvpairs=query.split("&") ret={} for kvpair in kvpairs: if '=' in kvpair: loc=kvpair.index('=') key,value=kvpair[:loc],kvpair[loc+1:] ret[key]=value return ret if __name__=='__main__': i=0 while True: i+=1 print "\nserve #%d:"%i serve(lambda *args:(args[2],200,'OK',{'Content-Type':'text/html'},'Go Away!')) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove multiple occurrences of a string within a list?
for item in listA: while item in listB: listB.remove(item) where listA is the list of things you want to remove from listB On 3 Apr 2007 11:20:33 -0700, bahoo <[EMAIL PROTECTED]> wrote: Hi, I have a list like ['0024', 'haha', '0024'] and as output I want ['haha'] If I myList.remove('0024') then only the first instance of '0024' is removed. It seems like regular expressions is the rescue, but I couldn't find the right tool. Thanks! bahoo -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Prevent Modification of Script?
If you are *really* worried about the database being attacked and edited, encrypt it by private key: require that the user set a password and use that password every time that s/he accesses the database. I am afraid that you cannot really prevent the database from being deleted completely, but you can stop it from being edited such that it actually contains readable information. I am repeating what someone else has already said, but how likely is it that someone will attack your program specifically with malware? The very worst that can happen is that someone replaces your application completely, and there is no way to prevent this. There are probably much better things to replace than your program (such as OS files that are run during startup). Perhaps now would be a good time for me to begin my rant about how security has all been gone about the wrong way within computers (network security is just fine, with the exception of WEP). Part I: the problem Firstly, it is possible to bypass all security in Windows (I only talk about windows because I have not used any other OS enough to know the security flaws, not because they are any better). This is because Windows runs on top of the bios, which runs on top of the hardware. Making calls to the bios or the hardware directly therefore bypasses Windows, and allows you to do anything that Windows might prevent you from doing (this is all theoretical, by the way). I have actually managed to log into other users of whom I do not know the password in Windows 98. It is quite simple, in fact I discovered it by accident. If that user was logged in last, and shut down the computer, you (1) start up the computer, (2) type in a few bogus passwords in the login screen and try to login with them, and (3) clear the password field, and press login. You will login as that previous user. Part II: what is wrong with this The OS should not be inhibiting users or programs from doing things. These things can be done anyway by bypassing it. This is a security flaw that can be fixed (and will be in a computer that I am in the process of designing: don't expect it to be on the market any time soon). Current security is like security written in javascript (client side). The browser checks a form against source code which is available to the user to see if the password is correct, and then goes to a page, the URL of which is also available to the user in the source code. My planned security is more like security written in php (server side). The browser submits the form, and the server checks it against a database, choosing the location which the browser goes to based on that. The location to which the browser is sent was not previously available to the user in the source code. It was safely hidden away in a remote database for which the user had no access. Part III: the solution Since I will be including the solution in my design for a computer, I can only vaguely explain it. When programs run, they will be given a password. When the program tries to connect to a piece of hardware, they must securely pass the password to that hardware. The hardware then decides what rights the program has to it based on the location of the password in a database. The OS will inhibit nothing. The hardware will inhibit everything. Not even the OS nor the hardware has access to the contents of the database: They can only compare passwords against it, just like anything else. -- http://mail.python.org/mailman/listinfo/python-list
Re: is it possible to give an instance a value?
In answer to this part of your question, how to make this work: Person.Address 'Sydney' >>>Person.Address.type '%String' >>>Person.Address = 'Canberra' >>>print Person.Address. Person.Address.type Canberra %String try using the __getattr__ method of the class: class objWithTypeAttr(object): ... def __getattr__(self,key): ... if key is not "type": ... return self.__dict__[key] ... else: ... return type(self.val) ... def __init__(self,val): ... self.val=val ... a=objWithTypeAttr("blah") a <__main__.objWithTypeAttr object at 0x00AE0CD0> a.val 'blah' a.type -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert an integer to a float?
How did the new division ever get approved?! That's not pythonic! What if you then need to divide two integers and find an element in a list or dict? It will give you an error! I know that at the moment it is not implemented unless imported from __future__, but I expect that it eventually might be. That would be a problem with backwards compatibility. On 2/27/07, Bjoern Schliessmann < [EMAIL PROTECTED]> wrote: [EMAIL PROTECTED] wrote: > def compareValue(n1, n2): > i1 = int(n1) > i2 = int(n2) > > dx = abs(i2 - i1)/min(i2, i1) > print dx > return dx < 0.05 You could also prepend from __future__ import division Regards, Björn -- BOFH excuse #237: Plate voltage too low on demodulator tube -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
jsString class
Hi all, Some of you may find this useful. It is a class I wrote that acts like the way strings do in JavaScript. It is a little buggy, and not complete, but could be useful. class jsString: def __init__(self,string): if string.__class__ is list: print "list:",string self.list=string else: print "string:",string self.list=[string] def __add__(self,other): try: r=self.list[:-1]+[self.list[-1]+other] except: r=self.list+[other] return jsString(r) def __mul__(self,other): try: r=self.list[:-1]+[self.list[-1]*other] except: r=self.list*other return jsString(r) def __len__(self): return len(str(self)) def __str__(self): r="" for obj in self.list: r+=str(obj) return r def __repr__(self): return str(self.list) -- http://mail.python.org/mailman/listinfo/python-list
Re: Gosper arithmetic in Python
By the way, there are some commented out portions of code in there which you can just remove, if you want. The last two lines of the program are unnecessary, as well. On 2/12/07, Subscriber123 <[EMAIL PROTECTED]> wrote: Speaking of useful home-made modules, I wrote this primitive module which does limited math with fractions. Anyone is welcome to expand on it or use it for any purpose. If anyone would like to submit it as a PEP to be added to the Python library of reference, that would be great. If anyone wishes to do that, I ask that you at least add me as a coauthor. Collin Stocks On 2/12/07, Marcin Ciura <[EMAIL PROTECTED]> wrote: > > Hello, > > I hacked together a module implementing exact real > arithmetic via lazily evaluated continued fractions. > You can download it from > http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py<http://www-zo.iinf.polsl.gliwice.pl/%7Emciura/software/cf.py> > an use as an almost drop-in replacement for the math module > if you don't care too much about performance. > I'd be happy to hear any feedback and suggestions. > > Cheers, >Marcin > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Gosper arithmetic in Python
Speaking of useful home-made modules, I wrote this primitive module which does limited math with fractions. Anyone is welcome to expand on it or use it for any purpose. If anyone would like to submit it as a PEP to be added to the Python library of reference, that would be great. If anyone wishes to do that, I ask that you at least add me as a coauthor. Collin Stocks On 2/12/07, Marcin Ciura <[EMAIL PROTECTED]> wrote: Hello, I hacked together a module implementing exact real arithmetic via lazily evaluated continued fractions. You can download it from http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py an use as an almost drop-in replacement for the math module if you don't care too much about performance. I'd be happy to hear any feedback and suggestions. Cheers, Marcin -- http://mail.python.org/mailman/listinfo/python-list from math import sqrt class Fract(object): def __init__(self,*args): if len(args)==2: self.num,self.den=map(int,args) if len(args)==1: try:self.num,self.den=args[0].num,args[0].den except:self.num,self.den=int(args[0]),int(1) def __abs__(self): return Fract(abs(self.num),abs(self.den)) def __add__(self,other): other=Fract(other) x=self.change_den(self,other.den) y=self.change_den(other,self.den) return Fract(x.num+y.num,x.den) def __sub__(self,other): other=Fract(other) x=self.change_den(self,other.den) y=self.change_den(other,self.den) return Fract(x.num-y.num,x.den) def __div__(self,other): other=Fract(other) return Fract(self*self.invert(other)) def __mul__(self,other): other=Fract(other) return Fract(self.num*other.num,self.den*other.den) def __gt__(self,other): return float(self)>float(other) def __lt__(self,other): return float(self)=float(other) def __le__(self,other): return float(self)<=float(other) def __eq__(self,other): return float(self)==float(other) def __pow__(self,exp): x=self for i in range(1,exp): x=x*self return x def __float__(self): return float(self.num)/float(self.den) def __int__(self): return self.num/self.den def __str__(self): #print>>s,"string:",self.num,self.den self.simplify() return "%s/%s"%(self.num,self.den) def __repr__(self): #print>>s,"string:",self.num,self.den self.simplify() return "Fract(%s,%s)"%(self.num,self.den) def simplify(self): self.num,self.den=reduce(self.num,self.den) """ debug=[] debug.append((self.num,self.den)) for i in [self.num,self.den,2,3,5,7]: while self.num%i==0 and self.den%i==0 and self.num!=1 and self.den!=1: self.num/=i self.den/=i for i in xrange(11,int(sqrt(self.den))+3,2): while self.num%i==0 and self.den%i==0: self.num/=i self.den/=i if self.num==self.den!=1: print debug raise "the end" """ def invert(self,fraction): fraction=Fract(fraction) return Fract(fraction.den,fraction.num) def change_den(self,fraction,mult): return Fract(fraction.num*mult,fraction.den*mult) def scale(*args): mul=float(args[0]) args=list(args) length=len(args) dens=[] for arg in args: dens.append(arg.den) #print>>s,args for i in range(length): for j in range(length): if not i==j: args[i].num*=dens[j] args[i].den*=dens[j] nums=[] for arg in args:nums.append(arg.num) args=map(Fract,reduce(*nums)) #print>>s,args mul=float(args[0])/mul args.append(mul) #print>>s,args[0].den==args[1].den==args[2].den return args """ for j in range(len(args)): args2=list(args) for i in range(len(args)): #print>>s,i,j #print>>s,args,args2 args[i]*=args2[j].den dens=[] for arg in args:dens.append(arg.den) dens=reduce(*dens) for i in range(len(dens)):args[i].den=dens[i] #print>>s,args,args2 ##args[i].simplify() return args """ def reduce(*args): args=list(args) for i in [min(args),2,3,5,7]: divisible=True for j in range(len(args)):divisible=(divisible and (args[j]%i==0)) #print>>s,divisible,args,i if args[0]!=int(args[0]): raise Warning while divisible and min(args)!=1: for loc in range(len(args)):args[loc]/=i for j in range(len(args)):divisible=(divisible and (args[j]%i==0)) for i in xrange(11,int(sq