[issue25464] Tix HList header_exists should be "exist"

2015-10-22 Thread Rob Williscroft

New submission from Rob Williscroft:

The method header_exists of Tix HList raises:

File "...\python3\lib\tkinter\tix.py", line 926, in header_exists
return self.tk.call(self._w, 'header', 'exists', col)
_tkinter.TclError: unknown option "exists". Must be cget, configure, create, 
delete, exist or size

IOW the option should be "exist" not "exists".

I've seen this on Windows with python 2.7 and 3.4 and Linux-Mint with 2.7.6.

The current method "header_exists" doesn't seem to be referenced or documented 
anywhere.

--
components: Tkinter
files: Lib-tkinter-tix-header_exist.patch
keywords: patch
messages: 253357
nosy: rtw
priority: normal
severity: normal
status: open
title: Tix HList header_exists should be "exist"
type: crash
versions: Python 2.7, Python 3.4
Added file: http://bugs.python.org/file40842/Lib-tkinter-tix-header_exist.patch

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25464>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Sending a broadcast message using raw sockets

2013-01-22 Thread Rob Williscroft
Peter Steele wrote in
news:0c2b3482-df46-4324-8bf9-2c45d3f6b...@googlegroups.com in
comp.lang.python: 

 On Monday, January 21, 2013 1:10:06 AM UTC-8, Rob Williscroft wrote:
 Peter Steele wrote in
 
 news:f37ccb35-8439-42cd-a063-962249b44...@googlegroups.com in
 
 comp.lang.python: 
 
  I want to write a program in Python that sends a broadcast message

[snip]

 This is part of my Wake-On-Lan script:
 
 def WOL_by_mac( mac, ip = 'broadcast', port = 9 ):
 
[snip]
 
 Thanks for the code sample. Does this code work if the box has no IP
 or default route assigned? I'm away from the office at the moment so I
 can't test this. 

No idea, but the sockets system must be up and running before the 
card (interface) has an IP (otherwise how would it ever get assigned) 
and I presume DHCP works in a similar manner.
 
However the route assignemt is irrelevent, broadcast messages never 
get routed.

Rob
-- 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending a broadcast message using raw sockets

2013-01-22 Thread Rob Williscroft
Peter Steele wrote in
news:96947c45-f16b-4e97-b055-edc1241ee...@googlegroups.com in
comp.lang.python: 

 I just tried running you code, and the sendto call fails with
 Network is unreachable. That's what I expected, based on other tests
 I've done. That's why I was asking about how to do raw sockets, since
 tools like dhclient use raw sockets to do what they do. It can clearly
 be duplicated in Python, I just need to find some code samples on how
 to construct a raw packet. 
 

Try 
s = socket.socket( socket.AF_INET, socket.SOCK_RAW )

I tried this on windows and it needed admin privaleges to
run.

Rob.
-- 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending a broadcast message using raw sockets

2013-01-21 Thread Rob Williscroft
Peter Steele wrote in
news:f37ccb35-8439-42cd-a063-962249b44...@googlegroups.com in
comp.lang.python: 

 I want to write a program in Python that sends a broadcast message
 using raw sockets. The system where this program will run has no IP or
 default route defined, hence the reason I need to use a broadcast
 message. 
 
 I've done some searches and found some bits and pieces about using raw
 sockets in Python, but I haven't been able to find an example that
 explains how to construct a broadcast message using raw sockets. 
 
 Any pointers would be appreciated.

This is part of my Wake-On-Lan script:

def WOL_by_mac( mac, ip = 'broadcast', port = 9 ):
  import struct, socket

  a = mac.replace( ':', '-' ).split( '-' )
  addr = struct.pack( 'B'*6, *[ int(_, 16) for _ in a ] )
  msg = b'\xff' * 6 + addr * 16

  s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
  s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 )
  s.sendto( msg, ( ip, port ) )
  s.close()


The mac address is 6 pairs of hex digits seperated by '-' or ':'.

http://en.wikipedia.org/wiki/Wake-on-LAN



Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional decoration

2012-06-18 Thread Rob Williscroft
Roy Smith wrote in news:jro9cj$b44$1...@panix2.panix.com in 
gmane.comp.python.general:

 Is there any way to conditionally apply a decorator to a function?
 For example, in django, I want to be able to control, via a run-time
 config flag, if a view gets decorated with @login_required().
 
 @login_required()
 def my_view(request):
 pass

You need to create a decorator that calls either the original
function or the decorated funtion, depending on your condition, 
Something like (untested):

def conditional_login_required( f ):
  _login_required = login_required()(f)
  
  def decorated( request ):
if condition == use-login:
  return _login_required( request )
else:
  return f( request )
  
  return decorated

@conditional_login_required
def my_view(request):
  pass

Replace (condition == use-login) with whatever your run-time 
control flag is.

-- 
Rob.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ordering with duck typing in 3.1

2012-04-07 Thread Rob Williscroft
andrew cooke wrote in
news:33019705.1873.1333801405463.JavaMail.geo-discussion-forums@ynmm9 in
gmane.comp.python.general: 

 
 hi,
 
 please, what am i doing wrong here?  the docs say
 http://docs.python.org/release/3.1.3/library/stdtypes.html#comparisons
 in general, __lt__() and __eq__() are sufficient, if you want the
 conventional meanings of the comparison operators but i am seeing 
 
   assert 2  three
 E   TypeError: unorderable types: int()  IntVar()
 
 with this test:
 
 
 class IntVar(object):
 

 def __lt__(self, other):
 return self.value  other
 
 
 so what am i missing?
 

The part of the docs you are relying on uses the wording in general,
IOW, it is not saying that defining __eq__ and __lt__ will always be 
sufficient.

In this case the expression 2  three is calling int.__lt__, which
doesn't know how to comapre to an instance of your class so returns 
NotImplemented.

At this point if you had defined a __gt__ method the interpreter would then 
try and call that having first switched the arguments around.  But you 
didn't so a TypeError is raised.

I'm afraid I couldn't find anywhere in the docs where that behaviour is 
described, I suspect I only know it from lurking on usenet for a number of 
years.

The best description that I could find of the behaviour you are seeing is 
at:

http://docs.python.org/py3k/reference/expressions.html#not-in

There is a paragraph that contains:

... the == and != operators always consider objects of different types to 
be unequal, while the , , = and = operators raise a TypeError when 
comparing objects of different types that do not implement these operators 
for the given pair of types. ...

Perhapse the docs could be reworded to note that, to define a full set of 
comparisons between *different* types, you need to define a full set of 
special methods.

Some links I found along the way:

http://docs.python.org/release/3.1.3/library/constants.html?
highlight=__lt__#NotImplemented

http://code.activestate.com/recipes/576685/
http://docs.python.org/py3k/library/functools.html#functools.total_ordering

Rob.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot connect to IMAP server in Python 3.2

2012-04-04 Thread Rob Williscroft
Steven D'Aprano wrote in news:4f7d2475$0$3$c3e8...@news.astraweb.com in 
gmane.comp.python.general:

 I can connect to an IMAP server using Python 2.6:
 
 steve@runes:~$ python2.6 
 Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) 

 server = imaplib.IMAP4_SSL('x')
 
 But when I try with Python 3.2, it just sits there until it times out:

 server = imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT)
 
 What am I doing wrong?
 

Not using IMAP4_SSL, above you are using IMAP4 (non SSL) but with the 
SSL port.

http://docs.python.org/py3k//library/imaplib.html#imaplib.IMAP4_SSL

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Jack Trades wrote in
news:CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w...@mail.gmail.com
in gmane.comp.python.general: 

 def test():
  src = (
   def double(x):
return x * 2
 )
  globals  = {}
  exec( src, globals )
  return globals[ double ]

 print( test() )

 
 I looked into doing it that way but it still requires that the user
 use a specific name for the function they are defining.  The docs on
 exec say that an implementation may populate globals or locals with
 whatever they want so that also rules out doing a simple for item in
 globals, as there may be more than just the one function in there
 (though I suppose I may be able to work around that).
 
 

Why not just get the name from the user, or use a regular expression
to extract the first (or last, maybe) definition from the source string.

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Jack Trades wrote in news:CAG5udOiOAge3uHrGSDTZ412GAg+CC-
6u8igoyj0lnf3hnwu...@mail.gmail.com in gmane.comp.python.general:

  class CapturingDict(dict):
 ... def __setitem__(self, key, val):
 ... self.key, self.val = key, val
 ... dict.__setitem__(self, key, val)
 ...
  c = CapturingDict()
  exec(def myfunction(x): return 1, c)
  c.key
 'myfunction'
  c.val
 function myfunction at 0x100634d10

 HTH,

 --
 Arnaud

 
 That's brilliant and works flawlessly.  Thank you very much!

If an impementation (as you say up thread) can populate globals 
or locals with whatever they want, then how do you know that last 
item added was the function definition the user supplied ?

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Ethan Furman wrote in news:4e5d29c8.8010...@stoneleaf.us in 
gmane.comp.python.general:

 Jack Trades wrote:
 On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft wrote:
 If an impementation (as you say up thread) can populate globals
 or locals with whatever they want, then how do you know that last
 item added was the function definition the user supplied ?
 
 Because the implementation will add things before the exec is processed. 

How do you know this ?, it isn't what the docs say.

http://docs.python.org/reference/simple_stmts.html#the-exec-statement

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Arnaud Delobelle wrote in 
news:CAJ6cK1YVi3NQgdZOUdhAESf133pUkdazM1PkSP=p6xfayvo...@mail.gmail.com in 
gmane.comp.python.general:

 On 30 August 2011 13:31, Jack Trades jacktradespub...@gmail.com wrote:


 On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft r...@rtw.me.uk wrote:


  That's brilliant and works flawlessly. ¶ÿThank you very much!

 If an impementation (as you say up thread) can populate globals
 or locals with whatever they want, then how do you know that last
 item added was the function definition the user supplied ?

 That's not an issue. The last statement that is executed will be the
 def statement.

You don't know that, an implementation may for example set __bultins__ 
to None, prior to returning, its not an unreasonable thing to do and
the docs don't say they can't.

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-29 Thread Rob Williscroft
Jack Trades wrote in
news:CAG5udOg=GtFGPmTB=1ojnvnrpdyucxdokn1wjqmomv9gx0+...@mail.gmail.com
in gmane.comp.python.general: 

 ... I wanted to allow the user to manually return the
 function from the string, like this:
 
 a = exec(
 def double(x):
   return x * 2
 double
 )
 
 However it seems that exec does not return a value as it produces a
 SyntaxError whenever I try to assign it.

def test():
  src = (
  def double(x):
return x * 2
)
  globals  = {}
  exec( src, globals )
  return globals[ double ]
  
print( test() )

The a bove works on 2.7 (I tested it) on earlier versions you may need 
to use:

exec src in globals 

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Button Label change on EVT_BUTTON in wxpython!!!

2011-08-29 Thread Rob Williscroft
Ven wrote in news:aa1212bb-35e5-4bf9-b8ad-7a3c083749c2
@x2g2000yql.googlegroups.com in gmane.comp.python.general:

 So, here is what I did/want:
 
 self.run_button=wx.Button(self.panel,ID_RUN_BUTTON,label='Install')
 self.Bind(wx.EVT_BUTTON, self.OnRun,id=ID_RUN_BUTTON)
 
 def OnRun(self,evt):
  self.run_button.SetLabel('Installing..')
  #call a function that does the installation task
  installation_task()
  #After task completion, set the button label back to Install
  self.run_button.SetLabel('Install')
 
 When I try doing this, it doesn't set the label to Installing while
 the task is being performed. Any suggestions how do I achieve this?
 

http://wiki.wxpython.org/CallAfter

Using this your OnRun will become somthing like:

def OnRun( self, evt ):
  def after():
installation_task()
self.run_button.SetLabel('Install')
  self.run_button.SetLabel('Installing..')
  wx.Callafter( after )

However if installation_task takes a long time you will need to use
threads, something like (untested):

def OnRun( self, evt ):
  def after():
self.run_button.SetLabel('Install')
  def task():
installation_task()
wx.Callafter( after )

  self.run_button.SetLabel('Installing..')

  import threading
  threading.Thread( target = task ).start()

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.isdir do not work for Foder named '2011-07-03'

2011-07-18 Thread Rob Williscroft
Nulpum wrote in news:0bf400a3-735c-487a-8d74-
feb3b56be...@g5g2000prn.googlegroups.com in gmane.comp.python.general:

 I want to make sure that folder exists.
 '2011-07-03' is really exists. but 'os.path.isdir' say false
 Does anyone know why?
 
 os.path.isdir(C:\Users\Á¶Ã¢ÁØ\Desktop\logs)
 True
 os.path.isdir(C:\Users\Á¶Ã¢ÁØ\Desktop\logs\2011-07-03)
 False

Maybe it isn't a directory, but a file, what does os.path.exists() return.

Also could it be a Shortcut in which case 2011-07-03.lnk will exist.

Also have you left Hide extensions for known file types switched on,
in which case it may really be 2011-07-03.zip for example, a file 
not a directory even though Windows explorer shows it as a directory.

-- 
Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: None versus MISSING sentinel -- request for design feedback

2011-07-15 Thread Rob Williscroft
Steven D'Aprano wrote in news:4e1fd009$0$29986$c3e8da3
$54964...@news.astraweb.com in gmane.comp.python.general:

 I'm designing an API for some lightweight calculator-like statistics
 functions, such as mean, standard deviation, etc., and I want to support
 missing values. Missing values should be just ignored. E.g.:
 
 mean([1, 2, MISSING, 3]) = 6/3 = 2 rather than 6/4 or raising an error.

If you can't make your mind up then maybe you shouldn't:

MISSING = MissingObject()
def mean( sequence, missing = MISSING ):
  ...

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Addition problems

2011-04-01 Thread Rob Williscroft
vm wrote in news:in4m1u$hsc$1...@news2.carnet.hr in
gmane.comp.python.general: 

 def fun1(params_used_below_except_lk_and_lk2):
 lk = 0.0
 lk2 = 0.0
 for raw_data, hist, freq in raw_data_hist_list:
 lk2 = lk2 + fun2(some_constants_and_params_from_this_scope)
 q = fun2(same_args_as_before)
 lk = lk + q
 print lk, lk2
 
 For some set of input parameters, This function with specific input 
 prints out the same constant twice (as expected):
 
 15377.7424582 15377.7424582 (twice the same value)
 
 If I comment out lines q = fun2 and lk = lk + q, fun1, with the
 same parameters, prints:
 
 0.0 3.3469936856
 
 First value is expected, but I cannot understand how come the second 
 value is different in these two cases!

Clearly the value returned by fun2 (get_beta_func_fit_quality_hist_lk)
is different the second time you call it.

So it either depends on and modifies a global or a value referenced or 
contained in one of the arguments.

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess pipe question

2011-02-23 Thread Rob Williscroft
Rita wrote in
news:AANLkTi=88dcpm_kqrs2g620obsnxz0majubfwpeme...@mail.gmail.com in
gmane.comp.python.general: 

[Top post relocated]

 On Tue, Feb 22, 2011 at 7:57 PM, Rob Williscroft r...@rtw.me.uk
 wrote: 
 
 Rita wrote in
 news:AANLkTi=w95gxosc1tkt2bntgjqys1cbmdnojhokq4...@mail.gmail.com in
 gmane.comp.python.general:

 
  When using wait() it works a bit better but not consistent
  def run(cmd):
p=subprocess.Popen(cmd,stdout=subprocess.PIPE)
rc=p.wait()
print rc
return p.stdout
 

  When the output of cmd is a small ascii file it works perfectly
  fine, but when the file is large (more than 2MB) the process just
  waits for ever (I am guessing its blocking?).

 Your OS has supplied a pipe buffer of 2MB, its full and the prossess
 is waiting until you read something from the pipe (i.e.
 p.stdout.read()). 

 When I use the communicate call
  it works perfectly but my process is consuming way too much memory.
 
  Is there a better way to get my return code consistently
  efficiently and not take up so much memory?

 If you don't need the processes output then don't use the PIPE
 argument. If you do you will need to read from p.stdout until the
 process is complete, then get the return code:

 while True:
buf = p.stdout.read( 1024 )
# do somthing with buf
if len( buf )  1024:
break

 rc = p.wait()

 
 For extra points is there a way to speed up the p.stdout.read(bufsize)
 ? 

Its unlikely that is the problem, most likely you are reading all of the 
2MB OS pipe buffer and then having to wait for the programme you are 
calling to produce some more output.

Before trying to speed things up be sure to test with real work being 
done to the output you recieve.

If its still slow and you have multiple cores/processors then you will 
need to put you read loop in a thread to speed it up.

-- 
Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess pipe question

2011-02-22 Thread Rob Williscroft
Rita wrote in
news:AANLkTi=w95gxosc1tkt2bntgjqys1cbmdnojhokq4...@mail.gmail.com in
gmane.comp.python.general: 

 
 When using wait() it works a bit better but not consistent
 def run(cmd):
   p=subprocess.Popen(cmd,stdout=subprocess.PIPE)
   rc=p.wait()
   print rc
   return p.stdout
 

 When the output of cmd is a small ascii file it works perfectly fine,
 but when the file is large (more than 2MB) the process just waits for
 ever (I am guessing its blocking?).

Your OS has supplied a pipe buffer of 2MB, its full and the prossess 
is waiting until you read something from the pipe (i.e. p.stdout.read()).

When I use the communicate call
 it works perfectly but my process is consuming way too much memory.
 
 Is there a better way to get my return code consistently efficiently
 and not take up so much memory?

If you don't need the processes output then don't use the PIPE argument.
If you do you will need to read from p.stdout until the process is 
complete, then get the return code:

while True:
buf = p.stdout.read( 1024 )
# do somthing with buf
if len( buf )  1024:
break

rc = p.wait()

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list 2 dict?

2011-01-02 Thread Rob Williscroft
Octavian Rasnita wrote in news:0db6c288b2274dbba5463e7771349...@teddy in
gmane.comp.python.general: 

 Hi,
 
 If I want to create a dictionary from a list, is there a better way
 than the long line below? 
 
 l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b']
 
 d = dict(zip([l[x] for x in range(len(l)) if x %2 == 0], [l[x] for x
 in range(len(l)) if x %2 == 1])) 
 
 print(d)
 
 {8: 'b', 1: 2, 3: 4, 5: 6, 7: 'a'}

 dict( zip( l[ :: 2 ], l[ 1 :: 2 ] ) )
{8: 'b', 1: 2, 3: 4, 5: 6, 7: 'a'}

If you don't know about slice notation, the synatax I'm using above is:

list[ start : stop : step ]

where I have ommited the stop item, which defaults to the length of the
list.

http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-
list-tuple-bytearray-buffer-xrange

That will make 3 lists before it makes the dict thought, so if the
list is large:

 dict( ( l[ i ], l[ i + 1 ] ) for i in xrange( 0, len( l ), 2 ) )

may be better.

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if a module exists?

2010-11-06 Thread Rob Williscroft
Jon Dufresne wrote in 
news:aanlktikr5euhqpupa3yrid98oas92zfhk8u9lha5y...@mail.gmail.com in 
gmane.comp.python.general:

 try:
 import extension_magic_module
 except ImportError:
 pass
 else:
 handle_extension_magic_module()
 
 
 However, if the the extension module exists but throws an ImportError,
 due to a bug in the extension this idiom will mask the error and I
 will never see it.

import imp
try:
  m = imp.find_module( test_1 )
  if m[0]:
m[0].close()
except ImportError:
  pass
else:
  import test_1

http://docs.python.org/library/imp.html#imp.find_module

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dumping generator

2010-08-09 Thread Rob Williscroft
targetsmart wrote in news:cd83533b-f51e-4955-96c5-f8a10185bef1
@i18g2000pro.googlegroups.com in gmane.comp.python.general:

 Right now if I want to dump the contents of a generator object I use ,
 a snip from a bigger block of code..
 
 try:
  while gen:  print gen.next()
 except StopIteration:
  print Done
 else:
  raise
 
 is there a much simpler way ?

print list( gen ) 

 
 like for printing list we do
 list = range(10)
 print list
 would print
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pick items from list with probability based upon property of list member ?

2010-06-20 Thread Rob Williscroft
southof40 wrote in news:da3cc892-b6dd-4b37-a6e6-
b606ef967...@t26g2000prt.googlegroups.com in gmane.comp.python.general:

 I have list of of N Vehicle objects - the only possible vehicles are
 cars, bikes, trucks.
 
 I want to select an object from the list with a probability of : cars
 0.7, bikes 0.3, trucks 0.1.

Aside, all your probabilities add up to 1.1, they should add up to 1.
 
 I've currently implemented this by creating another list in which each
 car object from the original list appears 7 times, each bike 3 times
 and each truck once. I then pick at random from that list.

Aside, so 7 / 11 bikes, 3 / 11 cars and 1 / 11 trucks, are your 
actual probabilities.

But to answer your question, you could create 3 list, and then 
pick the list you draw from based on a random number then pick 
the item from the list based on another random number:

r = ( random() * 11 )

if r   1:
  picklist = truck_list
elif r   4:
  picklist = bike_list
else:
  picklist = car_list

# now pick the final item from pick list.


Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UnicodeDecodeError having fetch web page

2010-05-26 Thread Rob Williscroft
Kushal Kumaran wrote in news:1274889564.2339.16.ca...@nitrogen in
gmane.comp.python.general: 

 On Tue, 2010-05-25 at 20:12 +, Rob Williscroft wrote:
 Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3
 @m21g2000vbr.googlegroups.com in gmane.comp.python.general:
 
  Hi,
  
  The code below is giving me the error:
  
  Traceback (most recent call last):
File C:\Users\Administratör\Desktop\test.py, line 4, in
module 
  UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position
  1: unexpected code byte
  
  
  What am i doing wrong?
 
 It may not be you, en.wiktionary.org is sending gzip 
 encoded content back, it seems to do this even if you set
 the Accept header as in:
 
 request.add_header( Accept, text/html )
 
 But maybe I'm not doing it correctly.
 
 You need the Accept-Encoding: identity header.
 http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html

Thanks, following this I did change the line to be:

request.add_header( Accept-Encoding, identity )

but it made no difference to en.wiktionary.org it just sent the
back a gzip encoded response.

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UnicodeDecodeError having fetch web page

2010-05-25 Thread Rob Williscroft
Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3
@m21g2000vbr.googlegroups.com in gmane.comp.python.general:

 Hi,
 
 The code below is giving me the error:
 
 Traceback (most recent call last):
   File C:\Users\Administratör\Desktop\test.py, line 4, in module
 UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1:
 unexpected code byte
 
 
 What am i doing wrong?

It may not be you, en.wiktionary.org is sending gzip 
encoded content back, it seems to do this even if you set
the Accept header as in:

request.add_header( Accept, text/html )

But maybe I'm not doing it correctly.

#encoding: utf-8
import urllib
import urllib.request

request = urllib.request.Request
(url='http://en.wiktionary.org/wiki/baby',headers={'User-
Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 
Firefox/2.0.0.11'} )

response = urllib.request.urlopen(request)
info = response.info()
enc = info[ 'Content-Encoding' ]
print( Encoding:  + enc )

from io import BytesIO
import gzip

buf = BytesIO( response.read() )
unziped = gzip.GzipFile( wahatever, mode = 'rb', fileobj = buf )
html = unziped.read().decode('utf-8')

print( html.encode( ascii, backslashreplace ) )

Rob.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe help

2010-05-11 Thread Rob Williscroft
jim-on-linux wrote in news:mailman.74.1273614703.32709.python-l...@python.org 
in comp.lang.python:

 python help,
 
 I'm open for suggestions.
 
 I'm using py2exe to compile a working program.
 
 The program runs and prints fine until I compile it with py2exe. 
 
 After compiling the program, it runs fine until it tries to import 
 the win32ui module, v2.6214.0. 
 
 Then, I get a windows error message:
 
 ImportError: Dll load failed:  
 This application has failed to start because 
 the application configuration is incorrect.
 Reinstalling the application may fix this problem.
 
 
 Anyone have the same problem with this?.

http://www.py2exe.org/index.cgi/Py2exeAndWin32ui

Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sublassing tuple works, subclassing list does not

2010-03-31 Thread Rob Williscroft
Frank Millman wrote in news:mailman.1360.1270018159.23598.python-
l...@python.org in comp.lang.python:

 I came up with a simple solution that seems to work -
 
 class MyTuple(tuple):
 ...   def __new__(cls, names, values):
 ... for name, value in zip(names, values):
 ...   setattr(cls, name, value)
 ... return tuple.__new__(cls, values)
 ...
 names = ['A', 'B', 'C']
 values = ['a', 'b', 'c']

 tup = MyTuple(names, values)


Are you aware you are adding attributes to the class here, IOW:

MyTuple.C == 'c'

If you want to add attibutes to the instance:

class MyTuple(tuple):
  def __new__(cls, names, values):
r =  tuple.__new__(cls, values)
for name, value in zip(names, values):
  setattr(r, name, value)
return r

names = ['A', 'B', 'C']
values = ['a', 'b', 'c']

tup = MyTuple(names, values)

assert tup[0] == 'a'
assert tup.B == 'b'

try:
  MyTuple.C
except AttributeError:
  pass
else:
  assert False



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: affectation in if statement

2010-03-16 Thread Rob Williscroft
samb wrote in news:5c361012-1f7b-487f-915b-0f564b238be3
@e1g2000yqh.googlegroups.com in comp.lang.python:

 Thanks for all those suggestions.
 They are good!
 
 1) Let's suppose now that instead of just affecting thing =
 m.group(1), I need to do a piece of logic depending on which match I
 entered...
 
 2) Concerning the suggestion :
 m = re.match(r'define\s+(\S+)\s*{$', line)
 if m:
 thing = m.group(1)
 
 m = re.match(r'include\s+(\S+)$', line)
 if m:
 thing = m.group(1)
 
 #etc...
 
 It means that I'll do all the checks, even if the first one did match
 and I know that the next will not...
 

Ths is how I did it when I had the need:

class ReMatch( object ):
  def __call__( self, pat, string ):
import re
self.match = re.match( pat, string )
return self.match is not None

clip = ...

re = ReMatch()

if re( r'\s*TM(\d+)', clip ):
  ...   
elif re( r'\s*(https?://.*)', clip ):
   ...
elif re( r'\d{12}$', clip ):
  ...

Rob.
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Method / Functions - What are the differences?

2010-02-28 Thread Rob Williscroft
Michael Rudolf wrote in news:hmdo3m$28...@news.urz.uni-heidelberg.de in 
comp.lang.python:

 Note that all I did was moving the list and foo into the instance. Still 
 no self and no cls, but also no static behaviour any more.

Yes in the first case foo was an attribute of the class, and in the second
an attribute of aon instance of the class.

In both cases it was a bound method, something similar too:

  lambda item : T.x.append( item )

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python crash on windows but not on linux

2010-02-12 Thread Rob Williscroft
hjebbers wrote in news:2864756a-292b-4138-abfd-
3348b72b7...@u9g2000yqb.googlegroups.com in comp.lang.python:

 the information about the error is a windows dump.

This may help:

# http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx

SEM_FAILCRITICALERRORS = 1
SEM_NOALIGNMENTFAULTEXCEPT = 4
SEM_NOGPFAULTERRORBOX = 4
SEM_NOOPENFILEERRORBOX = 8


import ctypes
from ctypes.wintypes import UINT

SetErrorMode = ctypes.windll.kernel32.SetErrorMode
SetErrorMode.restype = UINT
SetErrorMode.argtypes = ( UINT,)

Then putting:

SetErrorMode( SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX )

at the start of you programme, should stop the Critical Error dialog 
box you are seeing and you may get a chance to see a traceback.

Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem Regarding Queue

2010-02-09 Thread Rob Williscroft
mukesh tiwari wrote in news:80fed7d5-76eb-40c8-ace1-0c35736de399
@t17g2000prg.googlegroups.com in comp.lang.python:

 Could some one please tell what is wrong with this code. I am trying
 to use Queue in this program but i am getting error

The type you appear to be trying to use is Queue.Queue which you import
with:

from Queue import Queue 

http://docs.python.org/library/queue.html?highlight=queue#Queue.Queue

 Q_1=Queue()
 Q_2=Queue()
 Q_1.put(n)
 while(not Q_1.empty()):
 l=Q_1.get()
 if(rabin_miller(l)):
 Q_2.put(l)
 continue
 d=pollard(l)
 if(d==l):Q_1.put(l)
 else:

As the help page above points out also check out the deque Class:

http://docs.python.org/library/collections.html#collections.deque

Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pointless musings on performance

2009-11-24 Thread Rob Williscroft
mk wrote in news:mailman.915.1259064240.2873.python-l...@python.org in 
comp.lang.python:

 
 def pythonic():
 
 def unpythonic():
 
 
 Decidedly counterintuitive: are there special optimizations for if 
 nonevar: type of statements in cpython implementation?
 

from dis import dis

dis( unpythonic )

18  31 LOAD_FAST0 (nonevar)
 34 LOAD_CONST   0 (None)
 37 COMPARE_OP   9 (is not)
 40 JUMP_IF_FALSE4 (to 47)

dis( pythonic )

11  31 LOAD_FAST0 (nonevar)
 34 JUMP_IF_FALSE4 (to 41)
 
Rob.
 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pointless musings on performance

2009-11-24 Thread Rob Williscroft
mk wrote in news:mailman.923.1259070092.2873.python-l...@python.org in 
comp.lang.python:

 MRAB wrote:
 In what way is it counterintuitive? In 'pythonic' the conditions are
 simpler, less work is being done, therefore it's faster.
 
 But the pythonic condition is more general: nonevar or zerovar can be 
 '', 0, or None. So I thought it was more work for interpreter to compare 
 those, while I thought that is not None is translated to one, more 
 low-level and faster action. Apparently not.
 
 As Rob pointed out (thanks):
 
 11  31 LOAD_FAST0 (nonevar)
   34 JUMP_IF_FALSE4 (to 41)
 
 I'm no good at py compiler or implementation internals and so I have no 
 idea what bytecode JUMP_IF_FALSE is actually doing.

IIUC it implements:

http://docs.python.org/3.1/reference/expressions.html#boolean-operations

In the context of Boolean operations, and also when expressions are used 
by control flow statements, the following values are interpreted as false: 
False, None, numeric zero of all types, and empty strings and containers 
(including strings, tuples, lists, dictionaries, sets and frozensets). All 
other values are interpreted as true. User-defined objects can customize 
their truth value by providing a __bool__() method.

In particular its implementing ... Boolean operation ... used by 
control flow ..., all in one handy op code.

Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with database planning

2009-11-14 Thread Rob Williscroft
Juliano wrote in
news:0e64893a-af82-4004-bf3c-f397f2022...@g22g2000prf.googlegroups.com
in comp.lang.python: 

[snip]

 So, for ONE *concept*, we have, usually, MANY *slots*, each *slot* has
 ONE *facet*, and each *facet* can have MORE THAN ONE *filler*.
 Besides, some *slots* and *fillers* are themselves *concepts*,
 creating a sort of recursive reference.

What I'm grokking from the data you show is that a Concept is
a table (or a python class), slots are attributes of the concept
and facets are the type of slot, finally the fillers are 
(mostly) the data.

But also you seem to have slots that represent relationships
between Concepts and other tables, in this case the slots
should be tables.

For example with the slot type INSTANCE-OF, what is 
OTHER-NIGER-KORDOFANIAN-LANGUAGE is it another concept or a 
list of concepts or a concept OTHER-NIGER-KORDOFANIAN and
a type LANGUAGE, I suspect you have a table Language
and also an table Region in there too.

It may be time to start thinking in terms of what you are 
modeling and what the entities are (as apposed to trying to
convert the data you have), once you have that, work out 
how to load that data from your current file and check
that you can query your model correctly.

Maybe something like (using a made up ORM):

class Concept:
  name = TextField()
  definition = TextField()

  primary_key = PrimaryKey( name )

class IsASlot: 
  concept = ForeignKey( Concept )
  is_a = ForeignKey( Concept )

  primary_key = PrimaryKey( concept, is_a )

class LexeSlot:
  concept = ForeignKey( Concept )
  value = TextField()

  primary_key = PrimaryKey( concept, value )

class Region:
  region = TextField()  
  
  primary_key = PrimaryKey( region )

class Language:
  language = ForeignKey( Concept ) # or is it TextField() ?

  primary_key = PrimaryKey( language )

class LanguageOfSlot:
  language = ForeignKey( Language )
  region  = ForeignKey( Region )

  primary_key = PrimaryKey( language, region )


To reiterate, you should use your domain expertise to create
the model.

 
 begin table
 line_no concepts slots facets fillers
 ---
 --- 0 ABANDON DEFINITION VALUE to leave or
 desert something or someone
 1 ABANDON IS-A VALUE EXIT
 2 ABANDON LEXE MAP-LEX leave behind-V1
 3 ABANDON LEXE MAP-LEX abandon-V1

The -V1 in the above looks worryingly like you have structure embedded
in the data field, if so you should extract is so its in its own field 
or table.

 (...)
 97420 ZULU DEFINITION VALUE a language or dialect
 spoken in south africa and others
 97421 ZULU INSTANCE-OF VALUE
OTHER-NIGER-KORDOFANIAN-LANGUAGE 
 97422 ZULU LANGUAGE-OF INV LESOTHO
 97423 ZULU LANGUAGE-OF INV SOUTH-AFRICA 

Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating class objects inside methods

2009-10-04 Thread Rob Williscroft
Benjamin Kaplan wrote in news:mailman.838.1254682604.2807.python-
l...@python.org in comp.lang.python:

 And how do you just check a script's syntax without running it
 anyways?
 )
 
 Because these aren't compile-time errors. Python has no compilation
 phase- 

Sure it does, compilation happens for every script that is executed.

And for every import, if the pre-compiled byte code can't be found it 
is compiled (and the byte code saved as a .pyc or .pyo file).

Its only when a the interpreter has the complete compiled byte code
for a script or imported module that it executes anything.

Python could, if it was wanted, detect multiple syntax and other 
compilation errors, but AIUI the (CPython) developers choose not 
to, as it significantly simplifies (and thus speeds up) the 
compilation process, which can be significant for an interpreted
language.

For example I just ran a script with the one line:

print hello world

through IronPython (2.0 (2.0.0.0) on .NET 2.0.50727.3082)

I counted 1 and 2 and ... 12 before I seeing hello world

(Aside I think this is something that the current IronPython beta 
(2.6) fixes, but I havent tried it myself yet.)

 every statement (including def and class) is an executable

Yes but for example the execution of the statement:

def example() : pass

just assignes (binds) the compiled function to the name example.

 statement and it gets turned into byte code at execution time. Just
 like any other language, when Python hits a runtime error, it stops.
 

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send O(N**2) complexity

2009-09-21 Thread Rob Williscroft
Zac Burns wrote in news:mailman.211.1253559803.2807.python-l...@python.org 
in comp.lang.python:

 The mysocket.mysend method given at
 http://docs.python.org/howto/sockets.html has an (unwitting?) O(N**2)
 complexity for long msg due to the string slicing.
 
 I've been looking for a way to optimize this, but aside from a pure
 python 'string slice view' that looks at the original string I can't
 think of anything. Perhaps start and end keywords could be added to
 send? I can't think of a reason for the end keyword,  but it would be
 there for symmetry.
 

I ran this script on various versions of python I have access to:

#encoding: utf-8
raw_input( start )

s = 'x' * 100
r = [None] * 1000

raw_input( allocated 1 meg +  )

for i in xrange(1000):
  r[i] = s[:]

raw_input( end )

Niether of the CPython versions (2.5 and 3.0 (with modified code))
exibited any memory increase between allocated 1 meg +  and end

pypy-c (1.0.0) showed a 30k jump, and IronPython 2.0 showed a few megs
jump.

AIUI, as a python string is imutable, a slice of a string is a
new string which points (C char *) to the start of the slice data
and with a length that is the length of the slice, about 8 bytes
on 32 bit machine.

So even though a slice assignment new_s = s[:] appears to a python
programmer to make a copy of s, its only the a few bytes of 
metadata (the pointer and the length) that is really copied, the 
strings character data stays where it is.

So the code you cite is in fact O(N) as the copy is constant size.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send O(N**2) complexity

2009-09-21 Thread Rob Williscroft
 wrote in news:mailman.216.1253565002.2807.python-l...@python.org in 
comp.lang.python:

Niether of the CPython versions (2.5 and 3.0 (with modified code))
exibited any memory increase between allocated 1 meg +  and end
 
 You bumped into a special case that CPython optimizes.  s[:] is s.  If 
 you repeat your test with s[1:], you'll see memory climb as one might 
 normally expect.
 

Thanks for the correction (to Jack also)

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is the biggest number that i can send to Wave_write.writeframes(data)

2009-06-02 Thread Rob Williscroft
'2+ wrote in news:mailman.1017.1243932401.8015.python-l...@python.org in 
comp.lang.python:

 would like to take advantage of the wave module
 found a good example here:
 http://www.python-forum.org/pythonforum/viewtopic.php?f=2t=10644
 
 hmm .. i don't get how to write a stereo .. i mean i can set nchannels
 .. but how do i actually take control of each ch individually?

Interleave the channels, one sample for the left then one sample 
for the right (or maybe its the other way around).

 and what's the range(in float) of the data i can set in

The range of a signed 16 bit int, -2**15 to 2**15 - 1.

 wav_file.writeframes(struct.pack('h', data))?

Example:

import wave
from StringIO import StringIO

out = StringIO()

AMPLITUDE = 2 ** 15

w = wave.open( out, w )
w.setnchannels( 2 )
w.setsampwidth( 2 ) #BYTES
w.setframerate( 22000 )

from array import array
import math

F = 261.626
F2 = F * (2 ** (5 / 12.))
ang = 0.0
ang2 = 0.0
delta = ( math.pi * 2 * F  ) / 22000.0
delta2 = ( math.pi * 2 * F2  ) / 22000.0

for cycle in xrange( 4 ):
  data = array( 'h' )
  for pos in xrange( 22000 ):
amp = AMPLITUDE * (pos / 22000.0)
amp2 = AMPLITUDE - amp
if cycle  1:
  amp, amp2 = amp2, amp
  
data.append( int( ( amp * math.sin( ang ) ) ) )
data.append( int( ( amp2 * math.sin( ang2 ) ) ) )

ang += delta
ang2 += delta2
  
  w.writeframes( data.tostring() )
  
w.close()

sample = out.getvalue()
out.close()

#a wx player

import wx

app = wx.PySimpleApp()

class Frame( wx.Dialog ):
  def __init__( self, *args ):
wx.Dialog.__init__( self, *args )
b = wx.Button( self, -1, Ok )
b.Bind( wx.EVT_BUTTON, self.button )
  
  def button( self, event ):
self.sound = wx.SoundFromData( sample ) 
self.sound.Play( wx.SOUND_ASYNC )

frame = Frame( None )
frame.Show()

app.MainLoop()

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about regex

2009-05-30 Thread Rob Williscroft
 wrote in news:fe9f707f-aaf3-4ca6-859a-5b0c63904fc0
@s28g2000vbp.googlegroups.com in comp.lang.python:


  text = re.sub('(\(/?[^\]+)\)', , text)#remove the HTML
 

Python has a /r/ (raw) string literal type for regex's:

  text = re.sub( r'(\(/?[^\]+)\)', , text )

In raw strings python doesn't process backslash escape sequences
so r\n' is the 2 char' string '\\n' (a backslash folowed by an 'n').

Without that your pattern  string would need to be writen as:

  '(\\(/?[^\\]+)\\)'

IOW backslashes need to be doubled up or python will process them
before they are passed to re.sub.

Also this seems to be some non-python dialect of regular expression
language, Pythons re's don't need to escape  and .

http://docs.python.org/library/re.html

The grouping operators, '(' and ')', appear to be unnessasery,
so altogether this 1 line should probably be:

  text = re.sub( r'/?[^]+', '', text )

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite single transaction without foreign key or triggers

2009-05-13 Thread Rob Williscroft
John Machin wrote in news:b722bd36-c8f1-4cdf-8625-2550cee21511
@i28g2000prd.googlegroups.com in comp.lang.python:

 On May 13, 11:46 am, a...@pythoncraft.com (Aahz) wrote:
 In article xns9c09513903e8frtwfreenetremovec...@216.196.109.145,
 Rob Williscroft  r...@freenet.co.uk wrote:



 Aahz wrote innews:guao50$1j...@panix3.panix.comin comp.lang.python:
  In article xns9c08e179b66d8rtwfreenetremovec...@216.196.109.145,
  Rob Williscroft  r...@freenet.co.uk wrote:

 db.execute( '''
          update sessions set uid = ?
          where uid = ?
          and exists(
                   select * from users where uid  = ?
            )
     ''',
     (v['uid'],s.SID, v['uid'])
   )

  This will be more efficient if you do select uid from users.

 What will be more efficient ?

 Do you mean the select * ... or do you want to take the exists
 sub-query out and put it in a python if ?

 select uid will be more efficient than select *, although I
 suppose I could be wrong about that given how little I know about
 current query optimizers.

It seems the usual advice about premeture optimisation should apply,
namely write clear code (*), then optimise the bottlenecks when you 
actualy find you need to.

*) for some definition of clear code.

 My take is that it won't matter what you select if the optimiser is
 smart enough; something that requires minimal resources to produce is
 indicated in case the optimiser is dumb:
 
  ... exists (select 1 from ... )

I have to maintain some code writen by someone who thinks replacing 
* in queries with 1 is always a good idea (you know just in case), 
he wrote: 

select count(1) from ...

of course it didn't do what he thought it did.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite single transaction without foreign key or triggers

2009-05-12 Thread Rob Williscroft
Aahz wrote in news:guao50$1j...@panix3.panix.com in comp.lang.python:

 In article xns9c08e179b66d8rtwfreenetremovec...@216.196.109.145,
 Rob Williscroft  r...@freenet.co.uk wrote:

db.execute( '''
 update sessions set uid = ?
 where uid = ? 
 and exists(
  select * from users where uid = ?
   )
''',
(v['uid'],s.SID, v['uid']) 
  )
 
 This will be more efficient if you do select uid from users.

What will be more efficient ?

Do you mean the select * ... or do you want to take the exists 
sub-query out and put it in a python if ? 

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite single transaction without foreign key or triggers

2009-05-11 Thread Rob Williscroft
gert wrote in news:d7591495-4661-4243-ad7e-f142d8244e88
@e24g2000vbe.googlegroups.com in comp.lang.python:

 I am trying to do this in a single transaction, the 3 separate
 statements work fine, but i am screwed if they are not executed
 together.

Well you're in luck, Python DBAPI 2 connections handle this 
for you, you do need to call commit() on the connection though.

The default, for DBAPI 2 connections, is that all work occurs in a 
transaction (if the DB actually supports transactions) so you have to
call commit() on the connection after doing updates.

 
  ### db.execute('BEGIN') #
  db.execute('UPDATE users SET uid=? WHERE uid=?',(v['uid'],s.UID))

This is a fragile way to do it, your code won't work with a DB that
has real foreign keys (and maybe sqlite will get them one day).

A less fragile way of doing it is:

db = connection.cursor()

# First copy the row if it exists

db.execute( '''
insert into users
select ?, name, adress, city, country, phone, picture
from users where uid = ?
''', (v['uid'],s.UID)
  )

  db.execute('UPDATE sessions SET uid=? WHERE sid=?',(v['uid'],s.SID))

# Second update foriegn key tables to point to the new row
# (but only if the new row exists )

db.execute( '''
update sessions set uid = ?
where uid = ? 
and exists(
select * from users where uid = ?
  )
''',
(v['uid'],s.SID, v['uid']) 
  )

#Do the same for the groups table, then

# finally delete the original row (again only if the new row exists )

db.execute( '''
delete from users 
where uid = ?
and exists(
select * from users where uid = ?
  )
''',
(s.SID, v['uid']) 
  )

# Finally commit the transaction

connection.commit()

  # only do this if there is no primary key conflict in the above
  if db.ERROR == None: db.execute('UPDATE groups SET uid=? WHERE uid=?',
 (v['uid'],s.UID))

Python reports errors by throwing exceptions, so if you needed somthing
like this it would more likely be:

try:
  
  ... # somthing that errors up ...

catch sqlite3.DatabaseError:
  connection.rollback()

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyAA for Python2.5

2009-01-29 Thread Rob Williscroft
Kottiyath wrote in news:d86a0c1d-e158-4aa1-a47f-e2149948bdc3
@p2g2000prf.googlegroups.com in comp.lang.python:

 On Jan 29, 1:51 am, Rob Williscroft r...@freenet.co.uk wrote:
 Kottiyath wrote in news:6a594643-f6a2-4d8d-aab3-27eb16cb2fb8
 @b38g2000prf.googlegroups.com in comp.lang.python:


  I have mingw32-gcc in my path. If I try that too -it fails.

  C:\Documents and Settings\Guest\pyAApython setup.py install -c
  mingw32-gcc
  invalid command name 'mingw32-gcc'

 All the examples I found via google have the tool name as mingw32
 so try:

         python setup.py install -c mingw32

 Thank you Rob.
 The installation went ahead for some more time - but failed showing a
 lot of errors:
compile
 running build
 running build_py
 file pyAAc.py (for module pyAAc) not found
 file pyAAc.py (for module pyAAc) not found
 ...
 pyAAc.cpp:5887: error: `EVENT_OBJECT_HELPCHANGE' was not declared in
 this scope
 pyAAc.cpp:5888: error: `EVENT_OBJECT_DEFACTIONCHANGE' was not declared
 in this scope
 pyAAc.cpp:5889: error: `EVENT_OBJECT_ACCELERATORCHANGE' was not
 declared in this scope
 ...
 error: command 'gcc' failed with exit status 1
 
 I cannot understand why it fails. I have not worked in C till now, so
 I am pretty confused.
 I googled also, but to no avail.
 

Looks like the package needs some headers that haven't yet been 
ported to to MinGW.

Alas that meands you'll need to build with the Microsoft SDK 
and compiler.

You can get the SDK including a non-optimising compiler from:

http://www.microsoft.com/downloads/details.aspx?FamilyId=9B3A2CA6-3647-
4070-9F41-A333C6B9181Ddisplaylang=en

or maybe here:

http://www.microsoft.com/downloads/details.aspx?FamilyId=0BAF2B35-C656-
4969-ACE8-E4C0C0716ADBdisplaylang=en

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyAA for Python2.5

2009-01-28 Thread Rob Williscroft
Kottiyath wrote in news:6a594643-f6a2-4d8d-aab3-27eb16cb2fb8
@b38g2000prf.googlegroups.com in comp.lang.python:

 
 I have mingw32-gcc in my path. If I try that too -it fails.
 
 C:\Documents and Settings\Guest\pyAApython setup.py install -c
 mingw32-gcc
 invalid command name 'mingw32-gcc'
 

All the examples I found via google have the tool name as mingw32
so try:

python setup.py install -c mingw32

or

python setup.py build --compiler=mingw32 install


The compiler that the MinGW package installs is gcc.

You shoulf be able to verify it is on your path by typing: 

gcc --help
or 
gcc --version

and see some output.


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Start Python at client side from web app

2009-01-22 Thread Rob Williscroft
Thomas Guettler wrote in news:6tr453fca5h...@mid.individual.net in
comp.lang.python: 

 Diez B. Roggisch schrieb:
 
 2) create a localhost web server, for the client side manipulation.
 Then have your remote webserver render a form that posts via
 javavscript to the localhost webserver.  The localhost server would
 post back in
 the same way.
 
 AFAIK the JS security model prevents that.
 
 A page requested from http://myintranetserver/; can redirect to
 http://localhost:myport/myapp/?foo=...; 
 
 this would work.
 
 But how should the web server at localhost be started? You need to
 write a Windows service.

Since there will be only one client a regular programme 
should be fine.

   I guess that's not very easy, since I am not
 used to windows programming. 

Then don't do any (windows programming), do Python:

http://docs.python.org/3.0/library/wsgiref.html#module-
wsgiref.simple_server

http://docs.python.org/3.0/library/cgi.html#functions

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Start Python at client side from web app

2009-01-22 Thread Rob Williscroft
Diez B. Roggisch wrote in news:6ts0dnfc9s0...@mid.uni-berlin.de in
comp.lang.python: 

 Rob Williscroft schrieb:
 Diez B. Roggisch wrote in news:6tpo16fbacf...@mid.uni-berlin.de in
 comp.lang.python: 
 
 2) create a localhost web server, for the client side manipulation.
 Then have your remote webserver render a form that posts via
 javavscript to the localhost webserver.  The localhost server would
 post back in the same way.
 AFAIK the JS security model prevents that.

 
 Are you thinking of frames?, or the way IE 7 complains about 
 runnning javavscript (though it bizzarly calls it an running 
 an ActiveX control )?.
 
 Before posting, I tried a jQuery-ajax-call inside Firebug from some 
 random site to google. It bailed out with a security execption.

Yes the XMLHttpRequest object only allows you to make requests
to the same domain as the page came from.

Here is a concrete example of what I suggested:
 
body onload=document.forms[0].submit();
form action=http://localhost:8000/...;
input ...
/form
/body 

I.e. 1 line of JS that is manipulating the document of the page it
belongs to.

 
 And I found this:
 
 
 
 The Same-Origin Policy
 The primary JavaScript security policy is the same-origin policy. The 
 same-origin policy prevents scripts loaded from one Web site from 
 getting or setting properties of a document loaded from a different 
 site. This policy prevents hostile code from one site from taking
 over or manipulating documents from another. Without it, JavaScript
 from a hostile site could do any number of undesirable things such as
 snoop keypresses while you’re logging in to a site in a different
 window, wait for you to go to your online banking site and insert
 spurious transactions, steal login cookies from other domains, and so
 on. 
 
 http://www.windowsitlibrary.com/Content/1160/22/1.html
 
 Now there might be ways around this - but these sure are hacky, and
 not exactly the thing to look after.

That is scripting across frames (or windows), where the frames 
have a different origin (from different domain).

As an aside if the OP's app' can live with sending at most about 
1KB of ascii back and forth then using a HTTP redirect header is
another option.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: list subsetting

2009-01-21 Thread Rob Williscroft
culpritNr1 wrote in
news:mailman.7713.1232574803.3487.python-l...@python.org in
comp.lang.python: 

 
 Hello All,
 
 Say I have a list like this:
 
 a = [0 , 1, 3.14, 20, 8, 8, 3.14]
 
 Is there a simple python way to count the number of 3.14's in the list
 in one statement?
 
 In R I do like this
 
 a = c(0 , 1, 3.14, 20, 8, 8, 3.14)
 
 length( a[ a[]==3.14 ] )
 
 How do I do that in standard python?

count = a.count( 3.14 )

 
 (Note that this is just an example, I do not mean to use == in
 floating point operations.)

In this case something like this:

a = [0 , 1, 3.14, 20, 8, 8, 3.14]
count = sum( 1 for x in a if 3.13  x and x  3.15 )

http://docs.python.org/library/functions.html#sum
http://docs.python.org/reference/expressions.html#generator-expressions

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Start Python at client side from web app

2009-01-21 Thread Rob Williscroft
Thomas Guettler wrote in news:6toehtfbrb8...@mid.individual.net in
comp.lang.python: 

 Sorry, I described my problem not well. Here is more information:
 
 The main application is the intranet web application used with IE (ms
 windows client). But some action needs to be done on the client since
 you can't do it with html or javascript. 
 
 1. The user pushes a button in the web app.
 2. Webserver sends signed python code to the client with own mime type
 3. IE sends code to the python application.
 4. Signature gets checked, Python code on the client gets executed.
 5. Maybe send some data to the server with http.
 
  Thomas
 
 Server runs Linux with Django and Postgres.
 
 Thomas Guettler schrieb:
 Hi,
 
 I want to start Python at the client side from a web application. The
 app is an intranet application, and all client PCs are under our
 control (we can install software on them).
 
 But I don't want to update the installation too often. Here is my
 idea: 
 
 We create a custom mime-type and register it on the client PC. The
 web application can send signed python code to the client PC. If the
 signature is correct, the code will be executed at the client. The
 signature prevents others from executing code.
 
 Has someone seen or done something like this before?

Two options come to mind:

1) use a HTA as you client app,

http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx

The main drawback is it isn't a full browser so you loose things like 
back buttons, though some shortcuts F5 (refresh/reload) do work.

2) create a localhost web server, for the client side manipulation.
Then have your remote webserver render a form that posts via javavscript 
to the localhost webserver.  The localhost server would post back in
the same way.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Start Python at client side from web app

2009-01-21 Thread Rob Williscroft
Diez B. Roggisch wrote in news:6tpo16fbacf...@mid.uni-berlin.de in
comp.lang.python: 

 
 2) create a localhost web server, for the client side manipulation.
 Then have your remote webserver render a form that posts via
 javavscript to the localhost webserver.  The localhost server would
 post back in the same way.
 
 AFAIK the JS security model prevents that.
 

Are you thinking of frames?, or the way IE 7 complains about 
runnning javavscript (though it bizzarly calls it an running 
an ActiveX control )?.

Anyway it works fine.


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3: exec arg 1

2009-01-20 Thread Rob Williscroft
Alan G Isaac wrote in news:myhdl.805$aw2@nwrddc02.gnilink.net in 
comp.lang.python:

 On 1/18/2009 9:36 AM Alan G Isaac apparently wrote:
 I do not much care about the disappearance of ``execfile``.
 I was asking, why is it a **good thing** that
 ``exec`` does not accept a TextIOWrapper?
 Or is it just not implemented yet?
 What is the gain from this particular backwards
 incompatibility (in the sense that ``exec(open(fname))``
 no longer works)?
 
 Still interested in an answer...
 Alan Isaac

http://bugs.python.org/issue1762972 (*)

IIRC, exec(open(fname).read()) is the Py 3.0 replacement.

*) For reference, 2 clicks away from url:http://www.google.co.uk/search?
hl=enq=TextIOWrapper+exec+site%3Abugs.python.orgmeta=

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: function argument dependent on another function argument?

2009-01-18 Thread Rob Williscroft
Aaron Brady wrote in
news:6a10378f-addb-4d56-bc1b-0c382b3cb...@t26g2000prh.googlegroups.com
in comp.lang.python: 

 On Jan 18, 9:36 am, Paul Rubin http://phr...@nospam.invalid wrote:
 Steven D'Aprano st...@remove-this-cybersource.com.au writes:
  def foo(self, x, y=None):
      if y is None:
          y = self.a

  I don't find that clumsy in the least. I find it perfectly readable
  and 
  a
  standard idiom.

 That has the same problem as the earlier version.  If the person
 passes None, they get self.a.  I prefer:

     sentinel = object()
     ...

     def foo(x, y=sentinel):
       if y is sentinel:
           y = self.a
 
 It is too bad that it is so much work to detect whether 'y' was passed
 in the function call directly.  However, sentinel is just as good (or
 nearly); at worst, you need one sentinel per argument per function,

One per Module should be good enough. The only reason None doesen't
suffice is that it has other legitimate uses.  Though to be honest
I would always use None as the sentinel if it wasn't a legitimate
argument.

 which is possible to create, which has a specific meaning.  If you are
 making systematic function calls, e.g. with a dictionary or list, you
 can just use the sentinel in the dictionary.

IIUYC then, one sentinel is still only needed as the missing argument
is indicated by *both* position and value or by name and value (in the
case of a keyword-dictionary), so seperate distinct sentinel objects
aren't required, for example:

SENTINEL = object()

def f( a, b, c = SENTINEL, d = SENTINEL ):
  print( values: %r % ( ( a, b, c, d ), ) )
  if c is SENTINEL:
print( c is missing )
  if d is SENTINEL:
print( d is missing )

f( *( 1, 2, SENTINEL, SENTINEL ) )

f( **dict( a = 1 , b = 2, d = 4 ) )

f( **dict( a = 1 , b = 2, d = 4, c = SENTINEL ) )

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3: exec arg 1

2009-01-18 Thread Rob Williscroft
Steven D'Aprano wrote in news:018342f9$0$8693$c3e8...@news.astraweb.com
in comp.lang.python: 

 I'm not sure if this is a stupid question or not, but what's a 
 TextIOWrapper? In the example you give:
 
 exec(open(fname))
 
 the argument to exec -- open(fname) -- is a file object:
 
 type(open('hello.py'))
 type 'file'
 
 
 BTW, exec is a statement. The brackets there are totally superfluous.
 You can, and should, write: 
 
 exec open(fname)
 

You must have missed the subject line: Re: Python 3: exec arg 1

Python 3.0 (r30:67507, Dec  3 2008, 19:44:23) [MSC v.1500 64 bit (AMD64)] 
on win32
Type help, copyright, credits or license for more information.
 open( hello.py )
io.TextIOWrapper object at 0x0212F7F0
 exec a = 1
  File stdin, line 1
exec a = 1
   ^
SyntaxError: invalid syntax
 exec( a = 1 )
 a
1


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: function argument dependent on another function argument?

2009-01-18 Thread Rob Williscroft
Aaron Brady wrote in
news:582ef883-0176-4984-9521-6c1894636...@a26g2000prf.googlegroups.com
in comp.lang.python: 

 On Jan 18, 10:44 am, Rob Williscroft r...@freenet.co.uk wrote:
 Aaron Brady wrote
 innews:6a10378f-addb-4d56-bc1b-0c382b3cb...@t26g2000prh 
 .googlegroups.com
 in comp.lang.python:


  It is too bad that it is so much work to detect whether 'y' was
  passed in the function call directly.  However, sentinel is just as
  good (or nearly); at worst, you need one sentinel per argument per
  function, 

 One per Module should be good enough. The only reason None doesen't
 suffice is that it has other legitimate uses.  Though to be honest
 I would always use None as the sentinel if it wasn't a legitimate
 argument.

  which is possible to create, which has a specific meaning.  If you
  are
  making systematic function calls, e.g. with a dictionary or list,
  you can just use the sentinel in the dictionary.

 IIUYC then, one sentinel is still only needed as the missing argument
 is indicated by *both* position and value or by name and value (in
 the case of a keyword-dictionary), so seperate distinct sentinel
 objects aren't required, for example:

 SENTINEL = object()

 def f( a, b, c = SENTINEL, d = SENTINEL ):
   print( values: %r % ( ( a, b, c, d ), ) )
   if c is SENTINEL:
     print( c is missing )
   if d is SENTINEL:
     print( d is missing )

 f( *( 1, 2, SENTINEL, SENTINEL ) )

 f( **dict( a = 1 , b = 2, d = 4 ) )

 f( **dict( a = 1 , b = 2, d = 4, c = SENTINEL ) )

 
 I don't have a concrete example, so you may prove to be right, but I'm
 not convinced.

I'm afraid I can't think of a use case for passing default values around
eiither, and I suspect if we were to come up with one, a better solution
that didn't involve passing default values around could be found.
 
 If you have one function with an argument that defaults to an empty
 list, and calls another with an argument that defaults to an empty
 dict, then what is the meaning of passing sentinel to the first one?
 Whereas, if each had their own, then passing the first one's default
 would mean the empty list, and passing the second one's default would
 mean the dict.

If you *mean* to pass an empty list or empty dict's you should do 
it like:

  function_taking_list( [] )
  function_taking_dict( {} )

Its when you don't (have reason to) care that you need default arguments.

 (Or, even if that evaluates correctly, perhaps there is no such useful
 program.)

I agree, though I think some confusion arises here as there are two
(at least) distinct meanings for default arguments in python:

1) provide a value for when the caller doesn't, eg: 

def f( a = 1 ): ...

2) provide a cache for the functions /private/ use, eg:

def f( cache = {} ): ...

If the two are mixed up, then I can imagine a situation where somebody
might want to start passing default caches around.  It could only end
in tears.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mocking `from foo import *` functions

2009-01-10 Thread Rob Williscroft
 wrote in news:a9ed10ff-d907-46f0-8c6a-
c3d95579a...@k1g2000prb.googlegroups.com in comp.lang.python:

 To answer to Rob: yeah, sure that would work, but I always thought

Just to note: you're answering a question about testing, but I 
answered how to alter the alerter module *for* testing. given it
was the import * that was causing the OP the problem, I tried to
address that.

 mocking the imported function didn't feel right. The test then depends
 on the import method of the tested module. If you later change your
 mind and decide to use import sender and then sender.sendEmails(),
 you have to change your test code.

You have to add:

  import sender
  sender.sendEmails = mock_sendEmails

to your test script.

Note that doing the above *before* any other module imports
from sender, will be sufficient in *any* case, though it won't 
help if the tested code calls reload( sender ).

No need to scan every imported module for the mocked function.  

It also handles the case where other code imports the sender
module and calls sendEmails().

For additional robustness the above can be changed to:

  ## assert sender module hasn't been imported elsewhere yet
  
  import sys
  assert 'sender' not in sys.modules  

  import sender
  sender.sendEmails = mock_sendEmails

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mocking `from foo import *` functions

2009-01-09 Thread Rob Williscroft
Silfheed wrote in news:c73b304b-f601-4bb5-89c1-3ee667eeb7d9
@l37g2000vba.googlegroups.com in comp.lang.python:

 So I'm in the current testing situation:
 
 sender.py:
 -
 def sendEmails():
return I send emails
 
 alerter.py:
 -
 from sender import *
 def DoStuffAndSendEmails():
   doStuff()
   sendEmails()
 
 I'm trying to write a test fn that will test DoStuffAndSendEmails()
 (as well as it's kin) without actually sending any emails out.  I
 could go through alter alerter so that it does `import sender` and
 then find and replace fn() with sender.fn() so I can just create a
 mock fn fakeSendEmails() and and do something like sender.sendEmails =
 fakeSendEmails, but I'd rather not.
 
 Anyone know how to test alerter.py with out altering the file?

Yes you alter the module *after* you have imported it.

In your test script do:

  def mock_sendEmails():
pass # or some test code maybe

  # setup ...

  import alerter
  
  # now patch the module
  
  alerter.sendEmails = mock_sendEmails 

  # run the test ...

  DoStuffAndSendEmails()

Because python is dynamic alerter.DoStuffAndSendEmails will call 
the sendEmails in the alerter module that has been replaced with
mock_sendEmails from the test script.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator metadata/attributes

2009-01-08 Thread Rob Williscroft
 wrote in news:053df793-9e8e-4855-aba1-f92482cd8922
@v31g2000vbb.googlegroups.com in comp.lang.python:

 class TaggedWrapper():
 
 def __init__(self, generator, logMixin, stream):
 self.__generator = generator
 self.__tag = '%...@%s' % (logMixin.describe(), stream)
 logMixin._debug('Created %s' % self)

Note that self in the above is the instance of the wrapper class 
TaggedWrapper, not the class that is having its (generator) method
decorated.

import logging
logging.basicConfig( level = logging.DEBUG )

def mydecorator( f ):
  def decorated(self, *args):
logging.debug( Created %s, self.__class__.__name__ )
for i in f(self, *args):
  yield i
  return decorated
  
class Example( object ):
  @mydecorator
  def foo(self, a, b, ):
yield 1 + a + b

e = Example()
for i in e.foo( 2, 3 ):
  print( i )


Output of the above is:

DEBUG:root:Created Example
6

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator metadata/attributes

2009-01-07 Thread Rob Williscroft
 wrote in news:d301c93a-8a73-4cbb-9601-fe0c18a94f97
@v5g2000prm.googlegroups.com in comp.lang.python:

 I realise I could create my own wrapper that implements __next__ (I am
 using Python 3 and haven't checked the exact interface required, but I
 guess it's something like that), and add the information that way, but
 I am worried I am doing something too complicated.  Is there really no
 way to stick some arbitrary data onto a generator (from a function
 that yields)?
 
 In case it's any help, the decorator is basically:
 
 def mydecorator(f):
   def decorate(self, *args):
 generator = f(self, *args)

You can use something like this:

def mydecorator( f ):
def decorated(self, *args):
  for i in f(self, *args):
yield i
decorated.__doc__ = 'madeup doc string'
return decorated
  
class Example( object ):
  @mydecorator
  def foo(self, a, b, ):
yield 1

print( help( Example ) )

But realise that when the decorator (mydecorator above) is
run neither the class (Example) or the instance (self) is
available.  Which limits somewhat the debugging information 
you can attach automatically.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 nonlocal statement

2009-01-06 Thread Rob Williscroft
Matimus wrote in news:2a3d6700-85f0-4861-84c9-9f269791f044
@f40g2000pri.googlegroups.com in comp.lang.python:

 On Jan 6, 5:31 am, Casey casey...@gmail.com wrote:
 In PEP 3104 the nonlocal statement was proposed and accepted for
 implementation in Python 3.0 for access to names in outer scopes.  The
 proposed syntax included an optional assignment or augmented
 assignment to the outer name, such as:

 nonlocal x += 1

 This syntax doesn't appear to be supported in the 3.0 implementation.
 My question is: was this intentional or was it missed in the initial
 release?  If it was intentional, is there any plan to support it in a
 later 3.x release?  I realize it is a very small convenience feature
 but I have already come across a couple of cases where I use nested
 functions where it does make the code seem a little cleaner.

 Regards, Casey
 
 `nonlocal` should behave just like `global` does. It doesn't support
 that syntax either. So, yes it was intentional. No, there probably is
 no plan to support it in a later release.
 
 Matt
 

http://www.python.org/dev/peps/pep-3104/

quote
A shorthand form is also permitted, in which nonlocal is prepended to an 
assignment or augmented assignment:

nonlocal x = 3

The above has exactly the same meaning as nonlocal x; x = 3. (Guido 
supports a similar form of the global statement [24].)

/quote

Searching (AKA googling) for: nonlocal site:bugs.python.org
leads to: http://bugs.python.org/issue4199

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: About PyOpenGL

2009-01-05 Thread Rob Williscroft
trueli...@gmail.com wrote in news:f8099226-a953-4598-bfe2-61ee5772ce26
@l33g2000pri.googlegroups.com in comp.lang.python:

 
 Traceback (most recent call last):
   File test.py, line 36, in module
 main()
   File test.py, line 26, in main
 glutInit(sys.argv)
   File c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
 \OpenGL\GLUT\special.py, line 316, in glutInit
 _base_glutInit( ctypes.byref(count), holder )
   File c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
 \OpenGL\GLUT\special.py, line 57, in _base_glutInit
 return __glutInitWithExit(pargc, argv, _exitfunc)
   File c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
 \OpenGL\platform\baseplatform.py, line 280, in __call__
 self.__name__, self.__name__,
 OpenGL.error.NullFunctionError: Attempt to call an undefined function
 __glutInitWithExit, check for bool(__glutInitWithExit) before calling

To get you code running I needed (in addition to the PyOpenGL download)
to download. 

glut-3.7.6-bin.zip (117 KB) from http://www.xmission.com/~nate/glut.html

and put the glut32.dll where python can find it, the readme says
windows\system which worked, but sticking it in the same directory 
as python.exe (c:\python25 in your case) worked too.

http://pyopengl.sourceforge.net/
http://pyopengl.sourceforge.net/documentation/installation.html

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Triple quoted string in exec function ?

2008-12-30 Thread Rob Williscroft
Stef Mientki wrote in news:mailman.6399.1230668197.3487.python-
l...@python.org in comp.lang.python:

 And, by the way, exec is a *statement*, not a function!
 
   exec ( Init_Code, PG.P_Globals )
 
 I've really doubt that this is a statement,
 unless I don't understand what a statement is.
 
 

In python 2.x the above is a statement that is passed a tuple:

http://docs.python.org/reference/simple_stmts.html#exec

its a statement like print is:

 print ( 1,2 )
(1, 2)


In 3.x it is a function:

http://docs.python.org/3.0/library/functions.html#exec

print is also a function in python 3.x, so:

 print(1, 2)
1 2


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Triple quoted string in exec function ?

2008-12-30 Thread Rob Williscroft
Steven D'Aprano wrote in news:016abfa1$0$6988$c3e8...@news.astraweb.com in 
comp.lang.python:

 On Tue, 30 Dec 2008 15:35:28 -0600, Rob Williscroft wrote:
 
 Stef Mientki wrote in news:mailman.6399.1230668197.3487.python-
 l...@python.org in comp.lang.python:
 
 And, by the way, exec is a *statement*, not a function!
 
   exec ( Init_Code, PG.P_Globals )
 
 I've really doubt that this is a statement, unless I don't understand
 what a statement is.
 
 
 
 In python 2.x the above is a statement that is passed a tuple:
 
  http://docs.python.org/reference/simple_stmts.html#exec
 
 
 The documentation doesn't say anything about it accepting a tuple as an 
 argument. The tuple argument works in both 2.5 and 2.6. Curious.
 

My mistake, it is also behaving as a function:

http://docs.python.org/dev/3.0/whatsnew/3.0.html#removed-syntax

Removed keyword: exec() is no longer a keyword; it remains 
as a function. (Fortunately the function syntax was also accepted 
in 2.x.) Also ...

Though that was the only documentation of it I found in a brief 
web search.

 I was also surprised by this behaviour:
 
 g, l = {}, {}  # no globals, no locals
 exec x = 1 in g, l
 l
 {'x': 1}
 g.keys()
 ['__builtins__']
 
 I see *now* that this is documented:
 
 ...the current implementation MAY add a reference to the dictionary of 
 the built-in module __builtin__ under the key __builtins__ (!).
 [emphasis added]
 
 but it's still rather disconcerting. That means that:
 
 exec some potentially dangerous code in {}, {}
 
 isn't as safe as I thought it was.

AIUI it isn't meant to be safe, it provides some data hiding
that is useful for programming purposes but isn't much use
for security. 

Another example of a security hole:

 def f():
...   print f()
...
 exec from __main__ import f; f()
f()


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can I return a non-zero status result from a python script?

2008-12-15 Thread Rob Williscroft
silverburgh.me...@gmail.com wrote in news:74b53da4-bf07-431b-898b-
49977f7a6...@r36g2000prf.googlegroups.com in comp.lang.python:

 Hi
 
 How can I return a non-zero status result from the script? Just do a
 return 1? at the end?
 

 import sys
 help( sys.exit )
Help on built-in function exit in module sys:

exit(...)
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).



Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'new' module deprecation in python2.6

2008-11-29 Thread Rob Williscroft
David Pratt wrote in news:mailman.4664.1227980181.3487.python-
[EMAIL PROTECTED] in comp.lang.python:

 import new
 
 class FirstBase(object):
  foo = 'bar'
  biz = 'baz'
 
 class SecondBase(object):
  bla = 'blu'
  buz = 'brr'
 
 attr = {
  'fiz': 'An attribute', 'fuz': 'Another one'}
 
 Test = new.classobj(
  'Test', (FirstBase, SecondBase), attr)

Test = type(
 'Test', (FirstBase, SecondBase), attr)

 
 class MyNewClass(Test):
  pass
 
 a = MyNewClass()
 
 print a.foo, a.buz, a.fiz, type(a)

print( ( a.foo, a.buz, a.fiz, type(a) ) )

py 3.0:
('bar', 'brr', 'An attribute', class '__main__.MyNewClass')
py 2.4
('bar', 'brr', 'An attribute', class '__main__.MyNewClass')

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: asp oddness , why specify ASP twice

2008-11-26 Thread Rob Williscroft
davidj411 wrote in news:a08906ab-ba98-4ce0-a5f9-330f4b287423
@z27g2000prd.googlegroups.com in comp.lang.python:

 
 for some reason this code works:
 *
 %@ LANGUAGE = Python%

The above is a Directive, in this case it tells ASP what language to use, 
but other options like the enocding of the script can be specified.

There can only be one directive block It must be the first thing in 
the asp file and it starts with an @ sign.

There is manual, http://msdn.microsoft.com/en-us/library/ms524664.aspx

Being MSDN I suggest you read it now as by next week microsoft will
have moved the content elsewhere (I'd add a smiley here, but it 
really isn't funny).

 %
 Response.Write (test)
 %

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strange output from list

2008-11-11 Thread Rob Williscroft
Steve Holden wrote in news:mailman.3804.1226412496.3487.python-
[EMAIL PROTECTED] in comp.lang.python:

 Shouldn't it be GROUP BY master.id? I would have thought that SQL
 would be sad about a non-aggregate (master.id) that's in the SELECT
 list but not also in the GROUP BY list.
 
 Well, I did say untested. But in SQL Server, for example, any field
 argument to COUNT() must be an aggregated column. So it may depend on
 the SQL implementation. I should really have said

You must mean an SQL Server other than the Microsofts one, as:

select count( aid ) as count
from table_1
group by aid

count
---
8
8
8
8
8
8
8
8

(8 row(s) affected)

and:

select count( aid ) as count
from table_1

count
---
64

(1 row(s) affected)

Like it should.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exact match with regular expression

2008-11-01 Thread Rob Williscroft
Lawrence D'Oliveiro wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 In message [EMAIL PROTECTED], Rob
 Williscroft wrote:
 
 Read (and bookmark) this:
 
 http://www.python.org/doc/2.5.2/lib/re-syntax.html
 
 Funny how you never get a thank-you when you tell people to RTFM.

Saying Thank You is what email is for, which in this case is
what Mr.SpOOn did:

 Read (and bookmark) this:
 
  http://www.python.org/doc/2.5.2/lib/re-syntax.html
 
  You want the 3rd item down about the $ special character.
 
 Great, thanks.
 When I read about the symbol in the tutorial I didn't realize 
 what was it for.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exact match with regular expression

2008-10-26 Thread Rob Williscroft
Mr.SpOOn wrote in news:mailman.3069.1225039892.3487.python-
[EMAIL PROTECTED] in comp.lang.python:

 Hi,
 I'd like to use regular expressions to parse a string and accept only
 valid strings. What I mean is the possibility to check if the whole
 string matches the regex.
 
 So if I have:
 
 p = re.compile('a*b*')
 
 I can match this: 'aabbb'
 
 m = p.match('aabbb')
 m.group()
 'aabbb'
 
 But I'd like to get None with this: 'aabb'
 Instead it matches the first part:
 
 m = p.match('aabb')
 m.group()
 'aab'

Read (and bookmark) this:

http://www.python.org/doc/2.5.2/lib/re-syntax.html

You want the 3rd item down about the $ special character.
 
 p = re.compile('a*b*$')
 m = p.match('aabb')
 m is None
True
 m = p.match('aabbb')
 m.group()
'aabbb'

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Perl/Python regular expressions vs. Boost.regex?

2008-10-23 Thread Rob Williscroft
 wrote in news:[EMAIL PROTECTED] in
 comp.lang.python: 

 A colleague wrote a C++ library here at work which uses the
 Boost.regex library.  I quickly discovered an apparent problem with
 how it searches. Unlike re.match the regex_match function in that
 library effectively anchors the match at both the start and the end. 
 Can other people confirm this? 
 
 Thx,
 
 Skip Montanaro
 

Quoting from : url:http://www.boost.org/doc/libs/1_36_
0/libs/regex/doc/html/boost_regex/ref/regex_match.html

quote
Important 

Note that the result is true only if the expression matches the whole of 
the input sequence. If you want to search for an expression somewhere 
within the sequence then use regex_search. If you want to match a prefix of 
the character string then use regex_search with the flag match_continuous 
set. 
 
/quote

So yes it does.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: pyparsing 1.5.1 released

2008-10-19 Thread Rob Williscroft
Paul McGuire wrote in
news:[EMAIL PROTECTED]
in comp.lang.python: 

 On Oct 18, 1:05 pm, Terry Reedy [EMAIL PROTECTED] wrote:
 Paul McGuire wrote:
  I've just uploaded to SourceForge and PyPI the latest update to
  (Python 3.0 uses syntax for catching exceptions that is
  incompatible with Python versions pre 2.6, so there is no way for
  me to support both existing Python releases and Python 3.0 with a
  common source code base.

 I thought 2to3.py was supposed to make that change automatically.
 Have you tried it and found it not to work?

 tjr
 
 Please re-read my caveat.  What I said was (or tried to anyway) was
 that I cannot write a source file that will work on 2.4, 2.5, 2.6, and
 3.0.  Actually, it was very close - but for the change in the except
 syntax, I could actually have pulled it off.
 
 I should probably use 2to3.py on my unit tests, so that my Py3 version
 of pyparsing can get tested more fully.  I'll also use 2to3.py on
 pyparsing.py itself, it will make it easier to maintain the Py3 source
 version.  (I'll still have to keep and support two different source
 versions though, pity.)
 

AIUI the idea is that you write your 2.x python code (and tests) so 
that when they are processed by 2to3.py you get valid python 3.x 
code that will pass all its tests.  

You then maintain your 2.x code base adding another test where the
code (and tests) is run through 2to3.py and then python 3.x runs
the test suite.

Presumably you only need to start maintining a 3.x code base when
you start adding 3.x specific features or abandon support for
2.x python.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: properties access by name

2008-10-17 Thread Rob Williscroft
=?KOI8-R?B?7cnU0Q==?= wrote in news:f1a77a69-2997-4f53-9a46-
[EMAIL PROTECTED] in comp.lang.python:

 
 class Film(object):
 def __init__(self, title):
 self.__title = title
 
 @getproperty
 def title(self):
 return self.__title
 @setproperty
 def title(self, value):
 self.__title = value
 
 properties_to_set = ['title']
 f = Film('aaa')

Ther is a builtin `setattr` to do this:

#http://www.python.org/doc/2.5.2/lib/built-in-funcs.html

setattr( f, title, bbb )

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading from stdin (in windows)

2008-10-14 Thread Rob Williscroft
[EMAIL PROTECTED] wrote in news:mailman.2448.1223974725.3487.python-
[EMAIL PROTECTED] in comp.lang.python:

 Hi!
 
 I wanna write a file processor in python (Windows XP).
 I wanna use pipe, and not parameters.
 
 When I write this:
 
 ...
 l = []
 while 1:
  t = sys.stdin.read(1)
  if t == '':
  break
  l.append(t)
 
 t = .join(l)
 ...
 
 and use code this:
 process.py test.txt
 
 I got:
 Bad file descriptor
 
 What I do wrong? I need to call this module in another format?
 Or I read in wrong way?
 

The problem appear to be that MS-Windows doesn't make pipe's for 
programs it opens via its file type association mechanism.

Essentially MS-Windows is treating the .py file as a document and
using python to open the document.

Try running you program as:

python process.py test.txt

Note for this to work python will have to be on your path.  If
it isn't use the full path to you copy of python. for e.g.:

c:\python25\python.exe process.py test.txt

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: csv files for download

2008-10-04 Thread Rob Williscroft
Bobby Roberts wrote in news:cdc29298-d005-4804-b407-81ecaf6bb1b4@
2g2000hsn.googlegroups.com in comp.lang.python:

 I need to be able to offer a client click to download functionality
 on their website.  Generating the data to provide to them is not an
 issue but I want them to be able to click a button and have the
 response be sent to a csv file which they are prompted to download.
 Can someone point me in the right direction how to do this in python.
 Thanks in advance.

Assuming your using WSGI (you don't say) it would be something like this:

def wsgi( environ, start_response ):
  start_response( '200 OK', [ 
  ('Content-Type','text/csv'),
  ('Content-Disposition', 'attachment; filename=whatever.csv') 
])
  ...

If your using cgi it will be something like:

print Content-Type: text/csv
print 'Content-Disposition: attachment; filename=whatever.csv'
print   
...

http://search.yahoo.com/search?p=Content-Disposition
http://www.python.org/doc/2.5.2/lib/cgi-intro.html

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: processing email with Python on Windows?

2008-10-03 Thread Rob Williscroft
Beliavsky wrote in news:d579f554-be4b-4066-acec-49a7bafb1046
@t41g2000hsc.googlegroups.com in comp.lang.python:

 I work for a financial company where we run Windows XP and read email
 using Microsoft Outlook 2003. I get daily files that come as email
 attachments from various counterparties. I save them as h:\firm_name
 \mmdd.csv . Would Python be a good tool to automate the process of
 saving reports, or would it be more convenient to use a Microsoft
 proprietary language such as VB or C#? Of course one factor is one's
 relative competence with the various languages.
 

Assuming your Outlook is using Exchange (or at least a IMAP server),
you can use imaplib in the standard library.

This example should list the messages and attachments in you InBox 
fot today.

EXCHANGE = '' #-- YOUR EXCHANGE SERVER HERE
EXCHANGE_PORT = 143 # default
USER = '' #-- YOUR USERNAME
PWD ='' #-- YOUR PASSWORD

import imaplib, email
from datetime import date

today = date.today().strftime( '%d-%b-%Y' )

imap = imaplib.IMAP4( EXCHANGE, EXCHANGE_PORT )
imap.login( USER, PWD )
imap.select( 'InBox' )

typ, data = imap.search( None, 'SINCE', today )
for num in data[0].split():
  typ, data = imap.fetch(num, '(RFC822)')
  msg = email.message_from_string(data[0][1])
  
  print ( %s, %s\n % ( num, msg['subject'] ) )
  for part in msg.walk():
if part.get_filename() is not None:
  print (   %s\n % part.get_filename() )

imap.close()
imap.logout()

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I set a callback in Python?

2008-09-08 Thread Rob Williscroft
catsclaw wrote in news:d797403a-e492-403f-933a-bd18ef53d5c0
@k13g2000hse.googlegroups.com in comp.lang.python:

 I can't for the life of me figure out how to set a callback in
 Python.  I have a class, which wraps another class.  The second class
 needs a callback assigned.  I don't want to use globals for it.
 Here's what I'd like to do:
 
 class MyWrapper:
 def get_login(self, username):
 return self.user, self.pass
 
 def __init__(self, user, pass):
 self.user = user
 self.pass = pass
 
 self.client = Client(connection string)
 self.client.callback_login = get_login
 
 ... but obviously, the Client class, when it calls the callback,
 doesn't pass a reference to the self object.  How do I do this?


use:
 self.client.callback_login = self.get_login


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Profiling weirdness: Timer.timeit(), fibonacci and memoization

2008-08-03 Thread Rob Williscroft
Steven D'Aprano wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 So the question is: whats going on with timeit.Timer ?
 
 As far as I can see, nothing. I think you have misunderstood the results 
 you got.

No, the answer is that is it repeats a million times.  It might better be
called repeat_one_million_times().

Or put another way, myself and the OP misinterpreted what the call 
t1.repeat( number = 1 ) did.

its a confusing API.

For the OP:

The call t1.timeit() is equivalent to t1.repeat( number = 100 ).

So it bennefits from memoization because the call *is* repeated, not
just called once like you intended.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Profiling weirdness: Timer.timeit(), fibonacci and memoization

2008-08-02 Thread Rob Williscroft
Stefaan Himpe wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 Nothing weird about this ...
 The difference will become larger as your input value becomes larger.
 
 You can easily understand why if you try to calculate fib(10) by hand,
 i.e. work through the algorithm with pencil and paper,
 then compare the work you have to do to the memoized version which just 
 takes fib(9) and fib(8) from memory and adds them together.
 

I think you missed the point.

The problem is that the un-decorated, loop only version takes 
35 seconds when called by timeit.Timer.  However if you apply
the decorator it takes less that a second.  In *both* cases
the function (fib) only gets called once.

Note, I timed the call fib(100) with time.clock() and got a
value of less than 1 ms, the memozed version takes about 10 
times longer.

So the question is: whats going on with timeit.Timer ?

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating through 2 files simultaneously

2008-07-27 Thread Rob Williscroft
 wrote in news:7ae96aff-c1a7-4763-8db7-
[EMAIL PROTECTED] in comp.lang.python:

 Hi folks,
 
 I am trying to tee off both stdout and stderr from a process run
 through Popen.
 As a test, I am first trying to print the output below:
 
 from subprocess import Popen,PIPE
 ...
 p1 = Popen(['cvs', 'update'], stdout=PIPE, stderr=PIPE)
 for (l1, l2) in zip(p1.stdout, p1.stderr):
 print '--' + l1,
 print '--' + l2,
 
 This doesn't work - probably because I cannot iterate through the
 pipes this way.
 
 I am new to Python, and I'd appreciate it if you could please explain
 why this
 doesn't work and/or suggest an alternate way to redirect stdout and
 stderr to a
 common place.
 
 My objective is for my code to print out stdout/stderr messages and at
 the same
 time redirect them to a log file.

From the manual url: http://docs.python.org/lib/node528.html:

stdin, stdout and stderr specify ... 
... Additionally, stderr can be STDOUT, which indicates that the stderr 
data from the applications should be captured into the same file handle 
as for stdout. 

So import STDOUT and make stderr=STDOUT in the Popen call, you will then
have one file/pipe to deal with p1.stdout.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Questions on 64 bit versions of Python

2008-07-26 Thread Rob Williscroft
Martin v. Löwis wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 The end result of that is on a 32-bit machine IronPython runs in a
 32-bit process and on a 64-bit machine it runs in a 64-bit process.
 
 
 That's probably not exactly true (although I haven't checked).
 
 When you start a .NET .exe program, the operating system needs to
 decide whether to create a 32-bit or a 64-bit process (assuming the
 processor supports 64-bit mode). 
 
 The Microsoft .NET commercial framework uses the PE architecture of the

Whats the Commercial framework ? I've only come accross 3, the 
standard 32 bit one and 2 64 bit variants. 

 executable to make that decision (or, rather, it doesn't decide at all,
 but the underlying OS decides). The C# compiler (more specifically, the
 assembly linker) offers a choice of setting the .NET architecture to
 Itanium, AMD64, x86, or any; people use typically any. This any
 choice is implemented by setting the PE architecture to any, and then
 indicating to the .NET run-time that any other architecture would be
 fine as well.
 
 As a consequence, an architecture-any executable launches as a 32-bit
 process on a 64-bit system. 


I just tested, I built a default C# forms app using the AnyCPU option
and it ran as a 64 bit app (no *32 in Task Manager), this is on XP64.

I have though installed the AMD64 version of the 2.0 framework and 
AFAICT neither windows update or the Visual Studio installer
will install that by default, you have to go get it your self.

   To have the executable launch as 64-bit
 code, you must tell csc.exe to create an AMD64 binary (say), which
 then means that the binary won't launch on a 32-bit system. I haven't
 checked, but my guess is that IronPython uses architecture-any
 executables (unless you adjust the build process).

I just started ipy.exe the 1.1 and 2.0B1, both ran as 64 bit processes

IronPython 1.1 (1.1) on .NET 2.0.50727.1433
Copyright (c) Microsoft Corporation. All rights reserved.


I don't know what happens if you have both 32 bit and 64 bit versions
of the framwork installed (presumably with slightly different minor 
version numbers) as I uninstalled the 32 bit version before I installed the
AMD64 version.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Questions on 64 bit versions of Python

2008-07-26 Thread Rob Williscroft
Martin v. Löwis wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 
 I just tested, I built a default C# forms app using the AnyCPU
 option and it ran as a 64 bit app (no *32 in Task Manager), this is
 on XP64. 
 
 I have though installed the AMD64 version of the 2.0 framework and 
 AFAICT neither windows update or the Visual Studio installer
 will install that by default, you have to go get it your self.
 
 Interesting. I only tested this in .NET 1.1. Perhaps they have changed
 something since. How exactly did you launch the program? Does it change
 if you use Python's os.spawn* to launch it?

If subprocess.call will do then I can report the same results, a
64 bit process, using 32 bit CPython 2.5 to call it.
 
Also if the programme (C#) is built with the 3.5 framework I 
get the same results, however interestingly there is no 64 bit 
build for the 3.5 framework (or at least I was unable to find one).

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list

Re: urllib and login with passwords

2008-07-26 Thread Rob Williscroft
Jive Dadson wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 Hey folks!
 
 There are various web pages that I would like to read using urllib, but 
 they require login with passwords. Can anyone tell me how to find out 
 how to do that, both in general and specifically for YouTube.com.
 

A typical pattern is submit a form to login and get a cookie back,
subsuquent request with the cookie set are then loged in.

import cookielib, urllib2

cj = cookielib.CookieJar()

opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj) )

page = opener.open( LOGIN_URL, data = LOGIN_FORM )
page.close()

page = opener.open( DOWNLOAD_URL )

print page.read() 
page.close()


You will need to work out what goes in LOGIN_FORM, it likely
something like:

LOGIN_FORM = username=namepassword=passsubmit-button=Some+value

where username, password and submit-button are the name of the 
controls on the form you would normally login from.

If the form has an enctype='multipart/form-data' then things
get a little more complex, possibly start here:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a bug in urlunparse/urlunsplit

2008-05-18 Thread Rob Williscroft
Alex wrote in news:09764c57-03ce-4ccb-a26d-
[EMAIL PROTECTED] in comp.lang.python:

 Hi all.
 
 Is there a bug in the urlunparse/urlunsplit functions?
 Look at this fragment (I know is quite silly):
 
 urlunparse(urlparse('www.example.org','http'))
 --- 'http:///www.example.org'
^

Try these 3:

  urlparse('www.example.org','http')
  urlparse('http://www.example.org','http')
  urlparse('//www.example.org','http')

The 1st returns www.example.org as the path part
with the other 2 its the location (domain) part.

Although it may not be immediately obvious that the result 
is correct, consider the follwing html fragment:

  img src=aaa.gif
  img stc=http://anothersite.com/bbb.gif;

If you were to use urlparse to parse the src attributes
you would want:

  ( '', '', 'aaa.gif', '','','' )
  ( 'http', 'anothersite.com', '/bbb.gif', '','','' )


Which AIUI is what urlparse does.


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: https and POST method

2008-04-11 Thread Rob Williscroft
Lorenzo Stella wrote in news:7956f925-1037-49ea-a360-b58d627ffb20
@z24g2000prf.googlegroups.com in comp.lang.python:

 Hi all,
 I'm trying to write a simple script for sending sms via vyke... I have
 to make a https
 connection and pass some data with the POST method, like this perl
 script does:

Curl maybe, http://pycurl.sourceforge.net/

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encoding/decoding issue with python2.5 and pymssql

2008-03-24 Thread Rob Williscroft
Tzury Bar Yochay wrote in news:3a6c32fe-e7c1-4230-882d-efb3415196c1
@b1g2000hsg.googlegroups.com in comp.lang.python:

 for example:
 the value
 'EE604EE3-4AB0-4EE7-AF4D-018124393CD7'
 is represent as
 '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9\xd7'
 

from uuid import *

u = UUID( bytes = '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9\xd7')
print u

u = UUID( bytes_le = '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9\xd7')
print u

The bytes_le version prints: ee604ee3-4ab0-4ee7-af4d-018124393cd7
so I guess, this is what mysql is returning.

http://docs.python.org/lib/module-uuid.html

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cost of unicode(s) where s is Unicode

2008-01-06 Thread Rob Williscroft
John Nagle wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

Does
 
  text = unicode(text)
 
 make a copy of a Unicode string, or is that essentially a
 free operation if the input is already Unicode?
 
 John Nagle
 

http://docs.python.org/lib/built-in-funcs.html#l2h-78

  ... More precisely, if object is a Unicode string or subclass it 
  will return that Unicode string without any additional decoding 
  applied. 
  ...


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who's to blame?

2008-01-03 Thread Rob Williscroft
Nicola Musatti wrote in news:92dfc2fc-0677-43c0-b34f-4f240fa40205
@e4g2000hsg.googlegroups.com in comp.lang.python:

Note there is a wxpython mailinglist/newsgroup:

news:gmane.comp.python.wxpython

[snip]
 problem lies in the fact that apparently ShowModal() does not return
 when either the Yes or the No buttons are pressed. Curiously, if you
 change the Yes and No buttons with the OK and Cancel ones that are
 currently commented everything works as expected.

This is because the wx.Dialog class has handlers for the wxID_OK
and wxID_CANCEL button identifiers, IIRC in windows the MS supplied
dialog procedure behaves this way.

 
 As the sbs_test_xrc.py file below is automatically generated by
 wxPython 2.8.6.1's XRCed tool from a XRC file which in turn is
 generated by wxFormBuilder (http://wxformbuilder.org/), I really cant
 figure out to whom I should report this problem, assuming I'm not
 missing some obvious mistake of mine, that is.

 class MainFrame(sbs_test_xrc.xrcMainFrame):
 def __init__(self, parent):
 sbs_test_xrc.xrcMainFrame.__init__(self, parent)
 self.button.Bind(wx.EVT_BUTTON, self.OnButton)

First you can make the dialog a member, you are showing and hiding it
so there is no need to create a new one every time OnButton is fired.

  self.dialog = sbs_test_xrc.xrcDialog(self)

  # now replace the defaults of ID_OK and ID_CANCEL
  #
  self.dialog.SetAffirmativeId( wxID_YES )
  self.dialog.SetEscapeId( wxID_NO )

Alternativly you could derive from xrcDialog as you are with
xrcMainFrame and do the above in the derived classes __init__.

 def OnButton(self, event=None):
 d = sbs_test_xrc.xrcDialog(self)
 ##if d.ShowModal() == wx.ID_OK:
 if d.ShowModal() == wx.ID_YES:
 self.Close()
 

http://www.wxpython.org/docs/api/wx.Dialog-class.html

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extracting files from an ISO image?

2008-01-02 Thread Rob Williscroft
Ant wrote in news:34a84caa-5387-40a2-a808-
[EMAIL PROTECTED] in comp.lang.python:

[snip]

 
 So I have two questions really:
 
 1) Is there a module out there for extracting files from an ISO?

There are command line programs that can do this:

  http://cdrecord.berlios.de/old/private/cdrecord.html

This (with isoinfo.exe from the above) will list all files in an 
iso image file:

  CD = path-to-iso
  import subprocess

  subprocess.call( [ isoinfo.exe, '-f', '-i', CD ] )

isoinfo.exe also has a switch to extract a file to stdout

One problem you may have is daemon tools will mount cd images that
aren't iso images, where as isoinfo appears to handle only genuine
iso file systems.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysqldb SELECT COUNT reurns 1

2007-12-27 Thread Rob Williscroft
SMALLp wrote in news:[EMAIL PROTECTED] in comp.lang.python:

 Hy! I nave another problem I can't solve!
 code
 
  import MySQLdb as mysql

 cursor = conn.cursor()
 sql = SELECT COUNT(*) FROM  + dataTable
 res = cursor.execute(sql)

I think you need to do:
res = cursor.fetchone()[0]


 print res
 
 code
 It prints 1, and there are 88 rows in table. SELECT works fine, but 
 SELECT COUNT(*) makes problems.
 
Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Connecting to SQL database

2007-12-20 Thread Rob Williscroft
bill ramsay wrote in news:[EMAIL PROTECTED] in
comp.lang.python: 

 Hi
 
 I have successfully connected to SQL2000 and MSDEE databases in the

 
 Conn = Dispatch('ADODB.Connection')
 Conn.ConnectionString = Provider=SQLNCLI;Server=10.1.1.2;
 Database=csrctest;Uid=bill;Pwd=bill

By default SQL 2005 doesn't enable the TCP/IP protocol, if your app'
is running on the same machine use either the machine name or a
period (.) and it will use the Shared Memory protocol.

You will also need the server instance name(*), so it would be:

  Provider=SQLNCLI;Server=.\SQLEXPRESS;Datab...

*) IIRC you can't install express as the Default instance so
this will be required.

If you need to enable TCP/IP use the SQL Server Configuration Manager
about 4 levels deep from the Start menu.  Remember to enable it for
the server and SQLNCLI.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I want py2exe not to create library.zip

2007-09-12 Thread Rob Williscroft
On Wed, 12 Sep 2007 22:09:30 +0200, Laszlo Nagy wrote:

 Hi,
 
 I want py2exe not to create library.zip. My reason is that the installed
 program will be a self updating program, and it must be able to download
 changes (newer python source files) from the server. So the files should
 not be in library.zip. I tried the --bundle option but apparently it can
 only be used to make the distribution __more__ bundled.

In your setup.py, after the call to setup(), use zipfile.ZipFile
to extract the library.zip into a directory called library then
delete the .zip.

I can't remember of the top of my head, but you may actually need
to rename the new directory to library.zip for your application
to work.

-- 
Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the current date, python 2.2

2007-06-15 Thread Rob Williscroft
On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote:

 Using python 2.2 what is the simplest way to get the current date value?
 I have looked in so many places. The question is often asked and the
 usual response indicates how to get the current date and time like
 
 now = time.localtime()
 
 I want just the date, like 2007-06-15. The value will go into a
 postgresql Date type column.

  import datetime
  d = datetime.date.today()
  d.isoformat()
 '2007-06-15'
  
 
Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the current date, python 2.2

2007-06-15 Thread Rob Williscroft
On Fri, 15 Jun 2007 14:46:20 -0700, nano wrote:

 In article [EMAIL PROTECTED], [EMAIL PROTECTED]
 says...
 On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote:
 
  Using python 2.2 what is the simplest way to get the current date
  value? I have looked in so many places. The question is often asked
  and the usual response indicates how to get the current date and time
  like
  
  now = time.localtime()
  
  I want just the date, like 2007-06-15. The value will go into a
  postgresql Date type column.
 
   import datetime
   d = datetime.date.today()
   d.isoformat()
  '2007-06-15'
   
   
 Rob.
 
 Thanks, I'd read that today() was only good for 2.3?

Right I missed that, though its actually the datetime module that
is new in 2.3.

This should do though:

  import time
  time.strftime( %Y-%m-%d )
 '2007-06-15'
  

-- 
Rob.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Connection acception with confirmation

2007-05-29 Thread Rob Williscroft
no`name` wrote in news:[EMAIL PROTECTED] 
in comp.lang.python:

 maybe someone have some ideas how to block first stdin in main
 function and get stdin from the thread when here is a new connection?
 

No, but you could instead use a Queue:

http://docs.python.org/lib/module-Queue.html

so that your main thread reads stdin and then uses an instance 
of Queue to post the 'y's and 'n's it recives to your server 
thread.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is wsgi ready for prime time?

2007-05-17 Thread Rob Williscroft
Ron Garret wrote in news:rNOSPAMon-B77D6B.12263417052007
@news.gha.chartermi.net in comp.lang.python:

 PACKAGE CONTENTS
  handlers
  headers
  simple_server
  util
  validate
 
 Reading the documentation can be useful sometimes. Recommending 
 http://docs.python.org/lib/module-wsgiref.html, too.
 
 I did read the documentation, but the documentation does not seem to 
 reflect reality, e.g.:
 
 wsgiref.util 
 Traceback (most recent call last):
   File stdin, line 1, in module
 AttributeError: 'module' object has no attribute 'util'
 

IDLE 1.2  
 import wsgiref.util
 wsgiref.util
module 'wsgiref.util' from '\Python25\lib\wsgiref\util.pyc'
 

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interesting list Validity (True/False)

2007-05-11 Thread Rob Williscroft
 wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

  [] == []
 True
  ['-o'] == []
 False
  ['-o'] == False
 False
 

To test wether something is true use if.
To test wether something is false use if not.

The python values True and False are for when you need to 
*store* a boolean value (for later testing).

I you want to to see if an arbitry expression would test as true
or false at the interactive prompt use bool():

 bool([])
False
 bool(['-o'])
True
 

There is *never* any need to write things like:

expression == True

or:
expression == False

Once you stop doing this things will become much simpler.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter get widget option value

2007-05-08 Thread Rob Williscroft
 wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 If I have a button widget
 
 w = Button(root, text = Button, state = 'disabled')
 
 How can I get the value of option 'state' from the widget 'w'.
 I want something like --
 
 print w.state   to print out  'disabled'
 

print w.cget( state )

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error when using Custom Exception defined in a different python module.

2007-05-06 Thread Rob Williscroft
 wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 Hi,
 
 I am hitting this error consistently and don't know why it's
 happening. I would like to define all exceptions for my project in one
 file and use them across the project. Here's a sample -
 
 exceptions.py -

 
 from exceptions import *

  raise MyException(Raise custom error)
 
 When the above is run, I get the following error -
 NameError: global name 'MyException' is not defined


When you get this kind of error, goto a python prompt
(type python at a command prompt, or click on IDLE)
and try this:

 import exceptions
 help( exceptions )

I got this response (clipped):

Help on built-in module exceptions:

NAME
exceptions - Python's standard exception class hierarchy.

Another common module name to avoid is test.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I use the config parser?

2007-05-05 Thread Rob Williscroft
 wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 Hi,
 I need a specific example. I have seen the docs, but I don't all the
 stuffs there.
 

 from ConfigParser import ConfigParser

 
 Now I want to know how to read a section, a section attribute's value,
 and to write thoses back after reading.
 

ConfigParser is derived from RawConfigParser, so you need
to look at RawConfigParser's docs here:

http://docs.python.org/lib/RawConfigParser-objects.html


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does not my wx.html.HtmlWindow work?

2007-04-08 Thread Rob Williscroft
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED] in
comp.lang.python: 

 Below are my source code:
 
 import wx
 import wx.html
 
 class MyHtmlFrame(wx.Frame):
 
 def __init__(self, parent, title):
 wx.Frame.__init__(self, parent, -1, title, size=(600,400))
 html = wx.html.HtmlWindow (self)
 if gtk2 in wx.PlatformInfo:
 html.SetStandardFonts()
 html.LoadPage(
 http://www.pythonthreads.com/articles/python/incorporating-into
 -wxpython-part-1.html) 
 
 app = wx.PySimpleApp()
 frm = MyHtmlFrame(None, Simple HTML Browser)
 frm.Show()
 app.MainLoop()
 
 It is just an example in the book wxPython in action. But every time
 when I try to get it run, my CPU is fully occupied, and there is no
 frame that comes into existence. Why?
 

I think your problem is that you call LoadPage before app.MainLoop() is
called, IOW you need to call LoadPage in an event handler:

import wx
import wx.html

class MyHtmlFrame(wx.Frame):
  
HOME = http://www.google.co.uk;

def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, size=(600,400))
self.html = wx.html.HtmlWindow (self)
if gtk2 in wx.PlatformInfo:
self.html.SetStandardFonts()
self.done_show = False
wx.EVT_IDLE( self, self.OnShow )
self.html.SetPage( 
a href='%s'Loading .../a % self.HOME
  )
  
def OnShow( self, event ): 
if self.done_show:
  return
self.done_show = True
self.html.LoadPage( self.HOME ) 

app = wx.PySimpleApp()
frm = MyHtmlFrame(None, Simple HTML Browser)
frm.Show()
app.MainLoop()

Note: the URL you loading takes ages to show, which is why I
use: http://www.google.co.uk above.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where to find wx package

2007-01-05 Thread Rob Williscroft
siggi wrote in news:[EMAIL PROTECTED] in
comp.lang.python: 

 Hi all,
 
 a newbie question:
 
 I have a program gui03A.py using wxPython, importing it such:
 from wxPython.wx import *
 
 The program works, but I get the warning message:
 
 gui03A.py:4: DeprecationWarning: The wxPython compatibility package
 is no longer  automatically generated or activly maintained.  Please
 switch to the wx package  as soon as possible.
 
 However, after extensive searching on www.python.org and Googling the
 web, I do not find any package with wx as its only name.
 
 Where can I get the wx package (for win32 XP)?

The wx package talked about above is also part of WxPython,
so you have already got it. To import it use:

import wx

You will need to translate all (well most) identifiers in
your programme from wxBlah to wx.Blah so:

class MyFrame( wxFrame ):
  pass

becomes

class MyFrame( wx.Frame ):
  pass

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: method names in __slots__ ??

2006-12-25 Thread Rob Williscroft
John Machin wrote in news:1167008799.074885.250770@
73g2000cwn.googlegroups.com in comp.lang.python:

 Given a = Adder(),
 a.tally = 0
 gets AttributeError: 'Adder' object attribute 'tally' is read-only
 a.notinslots = 1
 gets AttributeError: 'Adder' object attribute 'notinslots' is read-only
 
 So is there some magic class-fu going down here, or is this just a
 waste of memory space in the instances?
 

Haven't you, with your 2 examples above, answered your own question ?

Clearly from your example it doesn't make any difference if you add 
a class attribute to the slots, one way or another its as if you 
hadn't put it in there in the first place.

This will give the same error, which shows its about class attributes
and not just methods:

class Adder(object):

__slots__ = [
  'class_name'
]

class_name = 3


a = Adder()

a.class_name = 2

It would seem that the interpreter removes any names it finds as class 
attribute names from the list it finds in __slots__ before it creates
the instance.

Of course if my guessing above isn't good enough, we could look at 
the documentation:

  http://docs.python.org/ref/slots.html#l2h-218

__slots__ are implemented at the class level by creating descriptors 
(3.4.2) for each variable name. As a result, class attributes cannot be 
used to set default values for instance variables defined by __slots__; 
otherwise, the class attribute would overwrite the descriptor assignment. 

So its that the __slots__ assignment makes the descriptors and then the
subsiquent method defenitions and class attribute bindings remove them.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: method names in __slots__ ??

2006-12-25 Thread Rob Williscroft
John Machin wrote in
news:[EMAIL PROTECTED] in
comp.lang.python: 

 Rob Williscroft wrote:
 John Machin wrote in news:1167008799.074885.250770@
 73g2000cwn.googlegroups.com in comp.lang.python:

  Given a = Adder(),
  a.tally = 0
  gets AttributeError: 'Adder' object attribute 'tally' is read-only
  a.notinslots = 1
  gets AttributeError: 'Adder' object attribute 'notinslots' is
  read-only 
 
  So is there some magic class-fu going down here, or is this just a
  waste of memory space in the instances?
 

 Haven't you, with your 2 examples above, answered your own question ?
 
 No.
 

 Clearly from your example it doesn't make any difference if you add
 a class attribute to the slots, one way or another its as if you
 hadn't put it in there in the first place.
 
 Clearly? Not so. It takes up memory. A list of 1 million Adder
 instances takes up about 68 Mb (Python 2.5 on Windows XP). With the
 method names removed from the __slots__, it takes only about 44 Mb.
 [For comparison: with no __slots__ at all, it takes about 180 Mb]
 
68 - 44 = 24
24 / 4 = 6

So thats 6 pointers for 5 methods, probably 5 pointers and and 4 bytes
round up to the nearest allocation unit.

So the slots in the instance are staying arround, even though they 
are no longer accesable (see below).

[snip]

 It would seem that the interpreter removes any names it finds as
 class attribute names from the list it finds in __slots__ before it
 creates the instance.
 
 It doesn't seem so to me. If it did that, the memory usage would not
 increase.

It was a guess, and an incorrect guess, but thats why I quoted the 
docs below.

 

 Of course if my guessing above isn't good enough, we could look at
 the documentation:

   http://docs.python.org/ref/slots.html#l2h-218

 __slots__ are implemented at the class level by creating descriptors
 (3.4.2) for each variable name. As a result, class attributes cannot
 be used to set default values for instance variables defined by
 __slots__; otherwise, the class attribute would overwrite the
 descriptor assignment. 
 
 I have read that, before I posted. Asides:
 (1) It would be useful if it stated the empirically determined fact
 that the result is that the class attribute is thusly made read-only.
 (2) The second sentence is not a model of clarity.
 
 In any  case I can't see how the paragraph gives any support for your
 next statement:
 

 So its that the __slots__ assignment makes the descriptors and then
 the subsiquent method defenitions and class attribute bindings remove
 them. 
 
 Errrmmm ... if the descriptors are removed, how is it that the
 behaviour is read-only?

The descriptors are part of the class object, they are removed 
when the class attributes are rebound, further rebinding of 
the class attributes will work fine:

  Adder.tally = 0

They are not assignable in the instance as the class descriptors 
that would have forwarded the assignment to the instances slots have 
been replaced.

The memory usage is higher because the slots in the instance are 
still there even though the descriptors that would allow them to 
be assigned have been removed.
 
Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >