Re: Python XML and tables using math

2010-08-16 Thread Stefan Behnel

flebber, 16.08.2010 05:30:

I am looking at a project that will import and modify an XML file and
then export it to a table. Currently a flat file table system should
be fine.

I want to export the modified data to the table and then perform a
handful of maths(largely simple statistical functions) to the data and
then print out the resultant modified tables.

I was planning on using Python 2.7 for the project.

Has anyone used a guide to acheive something similar? I would like to
read up on it so I can assess my options and best methods, any hints
or tips?


That can usually be done in a couple of lines in Python. The approach I 
keep recommending is to use cElementTree (in the stdlib), potentially its 
iterparse() function if the file is too large to easily fit into memory, 
but the code won't change much either way.


You might want to skip through this list a bit, similar questions have been 
coming up every couple of weeks. The responses often include mostly 
complete implementations that you can borrow from.


Stefan

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


Re: Python why questions

2010-08-16 Thread Bob Martin
in 639663 20100815 120123 Lawrence D'Oliveiro 
l...@geek-central.gen.new_zealand wrote:
In message mailman.2084.1281741048.1673.python-l...@python.org, Ian Kelly
wrote:

 The ability to change the minimum index is evil.

Pascal allowed you to do that. And nobody ever characterized Pascal as
“evil”. Not for that reason, anyway...

Why do you refer to Pascal in the past tense?  I use it most days (Delphi  
Free Pascal).
-- 
http://mail.python.org/mailman/listinfo/python-list


errors and exception

2010-08-16 Thread Alan
Hello,

I am using things like:

except Exception as inst:

and

with open(myfile.txt) as f:
for line in f:
print line

Things that seems to be new in python 2.6 and higher, however reading
http://docs.python.org/tutorial/errors.html and this not clear when this new
syntaxes appeared.

My trouble is that I want to make something similar above compatible with
python 2.5, but when running python2.5 I got:

except Exception as msg:
  ^
SyntaxError: invalid syntax

If there's a way (e.g. from __future__ ..., inherited modified Exception
class, etc) that could give a solution to keep my code in python 2.6 syntax
as above but compatible with python 2.5, that would be appreciated.

Many thanks in advance,

Alan
-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
http://www.bio.cam.ac.uk/~awd28
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Working with PDFs?

2010-08-16 Thread MRAB

jyoun...@kc.rr.com wrote:
Just curious if anyone knows if it's possible to work with pdf documents 
with Python?  I'd like to do the following:


- Pull out text from each PDF page (to search for specific words)
- Combine separate pdf documents into one document
- Add bookmarks (with destination settings)

A few programs I've been looking at are pdfminer, pyPDF, etc from this 
link:

http://pypi.python.org/pypi?%3Aaction=searchterm=pdfsubmit=search

Originally, I was using AppleScript and JavaScript to do this in Acrobat. 
But now Acrobat 9 has broken this process and I can't seem to make it 
work.  I'd like to find other workarounds instead of having to rely on 
Adobe.



Have you tried OpenOffice?
--
http://mail.python.org/mailman/listinfo/python-list


Re: segfault with small pyqt script

2010-08-16 Thread Gelonida
Hi Hans-Peter,


It seems, that my other posts did not get through.

On 08/15/2010 11:17 PM, Hans-Peter Jansen wrote:
 For a starter, tell us the versions of python-sip, and python-qt4 or however 
 they're called in Ubuntu. For the record, 
 python-sip-4.10.5-1.1
 python-qt4-4.7.4-1.1
 doesn't show this behavior.
 
 Pete

The problem seems to be known for 4.7.2.
For simple code I managed to work around the issue.
For the real more complicated I didn't. So it seems
I'll have to avoid 4.7.2.

Please see below:

On 08/13/2010 09:11 AM, Gelonida wrote:
  Lee,
 
  On 08/13/2010 12:53 AM, Lee Harr wrote:
 
  I'm desperate. I'm having a real application, which fails rather
often
  when finishing it. I'm not sure, whether any serious problem
could be
  hidden behind it
 
  The script is a pyqt script, which segfaults most of the time on my
  ubuntu 10.4 linux 64 bit and I'm having trouble to understand why.
 
 
  Looks to be a known issue:
  http://www.google.com/search?q=pyqt+segfault+on+exit
  https://launchpad.net/bugs/561303
 
  The last activity on that bug is almost 2 months ago...
  Hopefully the fix will be distributed soon.
 
 
 
  This seems to be the problem.
 
 
  In my case I can workaround the issue by adding one line.
 
  if __name__ == __main__:
  app = QApplication([])
  myform = MyForm()
  myform.show()
  retcode = app.exec_()
  myform = None #  THIS IS THE WORK AROUND
  print last
 
For more complex multi widget examples it doesn't seem enough to just
destroy the main widget.
probably I had to recursively assign all widgets / dialogues sub widgets
to None.

So I'll just try to stay away from this pyqt release and stick with
older or newer ones.






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


[Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Standish P
[Q] How far can stack [LIFO] solve do automatic garbage collection and
prevent memory leak ?

Because a stack has push and pop, it is able to release and allocate
memory. We envisage an exogenous stack which has malloc() associated
with a push and free() associated with a pop.

The algorithm using the stack would have to be perfect to prevent
stack overflow or condition of infinite recursion depth. This would
involve data type checking to filter out invalid input. The task must
be casted in an algorithm that uses the stack. Then the algorithm must
be shown to be heuristically or by its metaphor, to be correct using
informal reasoning.

Are there any standard textbooks or papers that show stacks
implemented in C/C++/Python/Forth with malloc/free in push and pop ?
If Forth is a general processing language based on stack, is it
possible to convert any and all algorithms to stack based ones and
thus avoid memory leaks since a pop automatically releases memory when
free is an intrinsic part of it.

KR ANSI has the example of modular programming showing how to
implement a stack but he uses a fixed length array. It is also
possibly an endogenous stack. We look for an exogenous stack so that
element size can vary.

===
Standish P stnd...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: errors and exception

2010-08-16 Thread Gary Herron

On 08/16/2010 12:06 AM, Alan wrote:

Hello,

I am using things like:
except  Exception  as  inst:
and


The old syntax for exceptions still works in Python2.x (all versions).  
The new syntax works in Python2.6+  and Python3.


try:
whatever
except Exception,msg:  # Old syntax
print msg





with  open(myfile.txt)  as  f:
 for  line  in  f:
 print  line



You don't need the new fangled with statement if you want to be 
compatible with older versions of Python2.  (It's nice and convenient, 
but not necessary.)


f = open(myfile.txt)
for line in f:
  print line
f.close()   # This is what the with statement guarantees; so now just 
do it yourself



Gary Herron



Things that seems to be new in python 2.6 and higher, however reading 
http://docs.python.org/tutorial/errors.html and this not clear when 
this new syntaxes appeared.


My trouble is that I want to make something similar above compatible 
with python 2.5, but when running python2.5 I got:


except Exception as msg:
  ^
SyntaxError: invalid syntax
If there's a way (e.g. from __future__ ..., inherited modified 
Exception class, etc) that could give a solution to keep my code in 
python 2.6 syntax as above but compatible with python 2.5, that would 
be appreciated.


Many thanks in advance,

Alan
--
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
http://www.bio.cam.ac.uk/~awd28 http://www.bio.cam.ac.uk/%7Eawd28


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


Re: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Alf P. Steinbach /Usenet

* Standish P, on 16.08.2010 09:20:

[garble garble]


Nonsense article We look for an exogenous stack cross-posted to

  [comp.lang.c],
  [comp.lang.c++],
  [comp.theory],
  [comp.lang.python],
  [comp.lang.forth].

Please refrain from following up on Standish' article.


Cheers,

- Alf

--
blog at url: http://alfps.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Q] How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Stefan Behnel

Standish P, 16.08.2010 09:20:

We envisage an exogenous stack which has malloc() associated
with a push and free() associated with a pop.


What's your use case?

Stefan

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


Re: errors and exception

2010-08-16 Thread Daniel Urban
 f = open(myfile.txt)
 for line in f:
   print line
 f.close()   # This is what the with statement guarantees; so now just do
 it yourself

Not exactly. More like:

f = open(myfile.txt)
try:
for line in f:
print line
finally:
f.close()


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


Re: errors and exception

2010-08-16 Thread Chris Rebert
On Mon, Aug 16, 2010 at 12:29 AM, Gary Herron
gher...@islandtraining.com wrote:
 On 08/16/2010 12:06 AM, Alan wrote:
 Hello,
 I am using things like:
snip
 with open(myfile.txt) as f:
 for line in f:
 print line

 You don't need the new fangled with statement if you want to be compatible
 with older versions of Python2.  (It's nice and convenient, but not
 necessary.)

 f = open(myfile.txt)
 for line in f:
   print line
 f.close()   # This is what the with statement guarantees; so now just do
 it yourself

Well, technically the equivalent would be:

f = open(myfile.txt)
try:
for line in f:
print line
finally:
f.close()

It's just that the for-loop and print happen to be extremely unlikely
to throw exceptions; presumably the OP's actual code is more complex.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replace and inserting strings within .txt files with the use of regex

2010-08-16 Thread Νίκος
On 10 Αύγ, 01:43, MRAB pyt...@mrabarnett.plus.com wrote:
 Íßêïò wrote:
  D:\convert.py
    File D:\convert.py, line 34
  SyntaxError: Non-ASCII character '\xce' in file D:\convert.py on line
  34, but no
   encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor
  details

  D:\

  What does it refering too? what character cannot be identified?

  Line 34 is:

  src_data = src_data.replace( '/body', 'brbrcenterh4font
  color=green Áñéèìüò Åðéóêåðôþí: %(counter)d /body' )

 Didn't you say that you're using Python 2.7 now? The default file
 encoding will be ASCII, but your file isn't ASCII, it contains Greek
 letters. Add the encoding line:

      # -*- coding: utf-8 -*-

 and check that the file is saved as UTF-8.

  Also,

  for currdir, files, dirs in os.walk('test'):

     for f in files:

sctually its for currdir, dirs, filesin os.walk('test'):  thats whay
ti couldnt run!! :-)

After changifn this and made some other modification my convertion
script finally run!

Here it is for someone that might want a similar functionality.

==

#!/usr/bin/python
# -*- coding: utf-8 -*-

import re, os, sys


count = 520

for currdir, dirs, files in os.walk('d:\\akis'):

for f in files:

if f.lower().endswith(php):

# get abs path to filename
src_f = os.path.join(currdir, f)

# open php src file
f = open(src_f, 'r')
src_data = f.read()
f.close()

# Grab the id number contained within the php code and 
insert it
above all other data
found = re.search( r'PageID = (\d+)', src_data )
if found:
id = found.group(1)
else:
id = count =+ 1
src_data = ( '!-- %s --\n\n' % id ) + src_data

# replace php tags and contents within
src_data = re.sub( r'(?s)\?(.*?)\?', '', src_data )

# add template variables
src_data = src_data.replace( '/body', 
'brbrcenterh4font
color=green Αριθμός Επισκεπτών: %(counter)d /body' )

# open same php file for storing modified data
f = open(src_f, 'w')
f.write(src_data)
f.close()

# rename edited .php file to .html extension
dst_f = src_f.replace('.php', '.html')
os.rename( src_f, dst_f )
print ( renaming: %s = %s\n % (src_f, dst_f) )


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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Nick Keighley
this is heavily x-posted I'm answering from comp.lang.c

On 16 Aug, 08:20, Standish P stnd...@gmail.com wrote:

 [Q] How far can stack [LIFO] solve do automatic garbage collection and
 prevent memory leak ?

I'm having trouble understanding your question (I read your whole post
before replying). I strongly suspect the only connection your question
has with C is that you are using C as your implementation language. I
think you're trying to ask a question about memory management. You
might be better off asking your question in a general programming new
group such as comp.programming (sadly rather quiet these days).

Note that C doesn't do automatic garbage collection. Memory is either
freed on exit from a scope (stack-like memory lifetime) or explicitly
(using free()). Static memory is, conceptually, never freed.

 Because a stack has push and pop, it is able to release and allocate
 memory.

I'm not sure what you mean by some of the terms you use. In a sense a
pop *is* a release. The memory is no longer available for use.

 We envisage an exogenous stack which has malloc() associated
 with a push and free() associated with a pop.

exogenous? Why would you do this? Are you envisioning a stack of
pointers? The pointers pointing to dynamically allocated memory? Well,
yes, sure you could implement this in C. It isn't garbage collection
by any standard definition of the term.

 The algorithm using the stack would have to be perfect to prevent
 stack overflow or condition of infinite recursion depth.

the memory lifetimes must be stack-like (or close to stack-like)

 This would
 involve data type checking to filter out invalid input.

I'd be more concerned about the memory allocation/dealllocation
pattern rather than the data types.

 The task must
 be casted in an algorithm that uses the stack. Then the algorithm must
 be shown to be heuristically or by its metaphor, to be correct using
 informal reasoning.

why informal reasoning? Why not formal reasoning?

 Are there any standard textbooks or papers that show stacks
 implemented in C/C++/Python/Forth with malloc/free in push and pop ?

well it doesn't sound very hard...

 If Forth is a general processing language based on stack, is it
 possible to convert any and all algorithms to stack based ones and
 thus avoid memory leaks since a pop automatically releases memory when
 free is an intrinsic part of it.

don't understand the question.

   - is forth a general purpose language? Yes
   - are all algorithms stack based? No

some compuations simply need to hang onto memeory for a long time

alloc (obj1)
alloc (obj2)
alloc (obj3)

free (obj2)
long_computation()
free(obj3)
free(obj1)

this simply isn't stack based. the memory for obj2 cannot be reused on
stack based scheme whilst long_computation() is going on.

 KR ANSI has the example of modular programming showing how to
 implement a stack but he uses a fixed length array. It is also
 possibly an endogenous stack. We look for an exogenous stack so that
 element size can vary.

malloc the memory? I see no garbage collection in your post

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-16 Thread Roald de Vries

On Aug 15, 2010, at 11:51 PM, Ian Kelly wrote:

On Sun, Aug 15, 2010 at 4:36 PM, Baba raoul...@gmail.com wrote:

Hi Mel,

indeed i thought of generalising the theorem as follows:
If it is possible to buy n, n+1,…, n+(x-1) sets of McNuggets, for  
some
x, then it is possible to buy any number of McNuggets = x, given  
that

McNuggets come in x, y and z packs.

so with diophantine_nuggets(7,10,21) i would need 7 passes
result:53

but with (10,20,30) and 10 passes i get no result


You're on the right track.  In the case of (10,20,30) there is no
largest exactly purchasable quantity.  Any quantity that does not end
with a 0 will not be exactly purchasable.

I suspect that there exists a largest unpurchasable quantity iff at
least two of the pack quantities are relatively prime, but I have made
no attempt to prove this.


That for sure is not correct; packs of 2, 4 and 7 do have a largest  
unpurchasable quantity.


I'm pretty sure that if there's no common divisor for all three (or  
more) packages (except one), there is a largest unpurchasable  
quantity. That is: ∀ i1: ¬(i|a) ∨ ¬(i|b) ∨ ¬(i|c), where ¬(x| 
y) means x is no divider of y


Cheers, Roald
--
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Standish P
On Aug 16, 12:47 am, Nick Keighley nick_keighley_nos...@hotmail.com
wrote:
 this is heavily x-posted I'm answering from comp.lang.c

 On 16 Aug, 08:20, Standish P stnd...@gmail.com wrote:

  [Q] How far can stack [LIFO] solve do automatic garbage collection and
  prevent memory leak ?

 I'm having trouble understanding your question (I read your whole post
 before replying). I strongly suspect the only connection your question
 has with C is that you are using C as your implementation language. I
 think you're trying to ask a question about memory management. You
 might be better off asking your question in a general programming new
 group such as comp.programming (sadly rather quiet these days).

 Note that C doesn't do automatic garbage collection. Memory is either
 freed on exit from a scope (stack-like memory lifetime) or explicitly
 (using free()). Static memory is, conceptually, never freed.

  Because a stack has push and pop, it is able to release and allocate
  memory.

 I'm not sure what you mean by some of the terms you use. In a sense a
 pop *is* a release. The memory is no longer available for use.

  We envisage an exogenous stack which has malloc() associated
  with a push and free() associated with a pop.

 exogenous? Why would you do this? Are you envisioning a stack of
 pointers? The pointers pointing to dynamically allocated memory? Well,
 yes, sure you could implement this in C. It isn't garbage collection
 by any standard definition of the term.

I can clarify what I mean.

Most books implement a stack with a fixed length array of chars and
push chars into it, for eg kr.

I have a dynamically allocated array of pointers. The cons cell is
allocated as well as the data is allocated for every push and the
pointer points to its_curr_val.next.

Similarly, every pop would move the pointer to its_curr_val.prev. It
would also free the cons cell and the data after making a copy of the
data. Below I explain your point on memory hanging.

  The algorithm using the stack would have to be perfect to prevent
  stack overflow or condition of infinite recursion depth.

 the memory lifetimes must be stack-like (or close to stack-like)

  This would
  involve data type checking to filter out invalid input.

 I'd be more concerned about the memory allocation/dealllocation
 pattern rather than the data types.

  The task must
  be casted in an algorithm that uses the stack. Then the algorithm must
  be shown to be heuristically or by its metaphor, to be correct using
  informal reasoning.

 why informal reasoning? Why not formal reasoning?

  Are there any standard textbooks or papers that show stacks
  implemented in C/C++/Python/Forth with malloc/free in push and pop ?

 well it doesn't sound very hard...

  If Forth is a general processing language based on stack, is it
  possible to convert any and all algorithms to stack based ones and
  thus avoid memory leaks since a pop automatically releases memory when
  free is an intrinsic part of it.

 don't understand the question.

    - is forth a general purpose language? Yes
    - are all algorithms stack based? No

Does Forth uses stack for all algorithms ? Does it use pointers , ie
indirect addressing ? If it can/must use stack then every algorithm
could be made stack based.

 some compuations simply need to hang onto memeory for a long time

     alloc (obj1)
     alloc (obj2)
     alloc (obj3)

     free (obj2)
     long_computation()
     free(obj3)
     free(obj1)

 this simply isn't stack based. the memory for obj2 cannot be reused on
 stack based scheme whilst long_computation() is going on.

In theory the memory can be locked by a long_computation() . But a non-
stacked based algorithm can also ignore freeing a memory and cause
memory leak, just as an improper usage of stack cause the above
problem. The purpose of a stack is to hold intermediate results ONLY.
Only intermediate results should be below the long_computation, not
those that need not wait for it. That is why heuristic or metaphorical
thinking which considers all aspects simultaneously in a visual human
brain thinking has less chance of error in conceiving such solutions
than formal disjoint and symbolic thought.

  KR ANSI has the example of modular programming showing how to
  implement a stack but he uses a fixed length array. It is also
  possibly an endogenous stack. We look for an exogenous stack so that
  element size can vary.

 malloc the memory? I see no garbage collection in your post

a stack properly used does not need separate garbage collection.
freeing is an automatic part of calling pop.

Thats the superiority of a stack based algorithm over linked lists of
unrestricted kinds.

===
Standish P stnd...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


comp.lang.python

2010-08-16 Thread roshini begum
www.127760.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor -- pythonic text-editor

2010-08-16 Thread Kruptein
I still keep getting more downloads then usual which is awesome, but I
still don't get any kind of response!
please mail me or reply to this post with what you think, You can tell
me that the program sucks but if you want to, do it in such a way that
you also describe what exactly is the problem and not just say the
total


I really need some response because I'm working on version 0.2.1 and I
want to know what there should be changed/added
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Nick Keighley
On 16 Aug, 09:33, Standish P stnd...@gmail.com wrote:
 On Aug 16, 12:47 am, Nick Keighley nick_keighley_nos...@hotmail.com
  On 16 Aug, 08:20, Standish P stnd...@gmail.com wrote:

this is heavily x-posted I'm answering from comp.lang.c

I also note that another poster has suggested you are a troll/loon

you seem to be using some computer science-like terms but in an oddly
non-standard manner

   [Q] How far can stack [LIFO] solve do automatic garbage collection and
   prevent memory leak ?

no at all. How can a goldfish whistle?

  I'm having trouble understanding your question (I read your whole post
  before replying). I strongly suspect the only connection your question
  has with C is that you are using C as your implementation language. I
  think you're trying to ask a question about memory management. You
  might be better off asking your question in a general programming new
  group such as comp.programming (sadly rather quiet these days).

this still applies

  Note that C doesn't do automatic garbage collection. Memory is either
  freed on exit from a scope (stack-like memory lifetime) or explicitly
  (using free()). Static memory is, conceptually, never freed.

   Because a stack has push and pop, it is able to release and allocate
   memory.

  I'm not sure what you mean by some of the terms you use. In a sense a
  pop *is* a release. The memory is no longer available for use.

   We envisage an exogenous stack which has malloc() associated
   with a push and free() associated with a pop.

  exogenous? Why would you do this? Are you envisioning a stack of
  pointers? The pointers pointing to dynamically allocated memory? Well,
  yes, sure you could implement this in C. It isn't garbage collection
  by any standard definition of the term.

 I can clarify what I mean.

 Most books implement a stack with a fixed length array of chars and
 push chars into it, for eg kr.

this isn't inherent to a stack implementaion. A stack could be a
malloced block of memory or a linked list.

 I have a dynamically allocated array of pointers. The cons cell is

that *what*? Are you trying to implement Lisp in C or something. Try
comp.lang.lisp for some help there. Have you read Lisp In Small
Pieces? Good fun.

 allocated as well as the data is allocated for every push and the
 pointer points to its_curr_val.next.

I'm lost. What does a cons cell have to do with a fixed array of
pointers? Why do you need dynamic memory? Aren't cons cells usually of
fixed size? How can a Lisp-like language use a stack based memory
allocation strategy?

 Similarly, every pop would move the pointer to its_curr_val.prev. It
 would also free the cons cell and the data after making a copy of the
 data. Below I explain your point on memory hanging.

   The algorithm using the stack would have to be perfect to prevent
   stack overflow or condition of infinite recursion depth.

  the memory lifetimes must be stack-like (or close to stack-like)

   This would
   involve data type checking to filter out invalid input.

  I'd be more concerned about the memory allocation/dealllocation
  pattern rather than the data types.

   The task must
   be casted in an algorithm that uses the stack. Then the algorithm must
   be shown to be heuristically or by its metaphor, to be correct using
   informal reasoning.

  why informal reasoning? Why not formal reasoning?

   Are there any standard textbooks or papers that show stacks
   implemented in C/C++/Python/Forth with malloc/free in push and pop ?

  well it doesn't sound very hard...

   If Forth is a general processing language based on stack, is it
   possible to convert any and all algorithms to stack based ones and
   thus avoid memory leaks since a pop automatically releases memory when
   free is an intrinsic part of it.

  don't understand the question.

     - is forth a general purpose language? Yes
     - are all algorithms stack based? No

 Does Forth uses stack for all algorithms ?

don't know. Ask the Forth people. Some algoritms are fundamentally not
stack based. If you try to implement them in Forth then either some
memory isn't claimed as soon as possible (a leak) or there is some way
to to have non-stack based memory management.

 Does it use pointers , ie
 indirect addressing ? If it can/must use stack then every algorithm
 could be made stack based.

  some compuations simply need to hang onto memeory for a long time

      alloc (obj1)
      alloc (obj2)
      alloc (obj3)

      free (obj2)
      long_computation()
      free(obj3)
      free(obj1)

  this simply isn't stack based. the memory for obj2 cannot be reused on
  stack based scheme whilst long_computation() is going on.

 In theory the memory can be locked by a long_computation(). But a non-
 stacked based algorithm can also ignore freeing a memory and cause
 memory leak, just as an improper usage of stack cause the above
 problem. The purpose of a stack is to hold intermediate results ONLY.

no not really

 Only 

When the first line of a file tells something about the other lines

2010-08-16 Thread Egbert Bouwman
Often the first line of a file tells how to read or interpret the other
lines.
Depending on the result, you then have to ...
- skip the first line, or
- treat the first line in another special way, or
- treat the first line in the same way as the other lines.

I can handle this by opening the file twice,
the first time for reading the first line only.
I suppose there exists a more elegant solution.
Below is the structure of what I do now.
Please comment.

f = open(file_name,r)# eerste opening
file_line  = f.readline()
special = True if some_condition else False
f.close()

f = open(file_name,r)# tweede opening
if not special:
# use first line, read previously
stripped_line = file_line.strip()
else:
# skip first file_line, or treat in another special way:
f.next()
# read other lines:
for file_line in f:
stripped_line = file_line.strip()
# now do something with stripped_line
f.close()

egbert
-- 
Egbert Bouwman  
Keizersgracht 197-II
1016 DS  Amsterdam  
Tel 0(031)20 6257991

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


GSM to ISO / UCS2 to ISO

2010-08-16 Thread James Mills
HI all,

In an effort to avoid re-inventing the wheel so to speak
I was wondering if anyone's come across libraries/tools, etc
that achieve the same kind of functionality as the tools
library in this java app.

http://code.google.com/p/ipddump/source/browse/trunk/src/ipddump/tools/Gsm2Iso.java

Thanks,

cheers
James

-- 
-- James Mills
--
-- Problems are solved by method
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When the first line of a file tells something about the other lines

2010-08-16 Thread Peter Otten
Egbert Bouwman wrote:

 Often the first line of a file tells how to read or interpret the other
 lines.
 Depending on the result, you then have to ...
 - skip the first line, or
 - treat the first line in another special way, or
 - treat the first line in the same way as the other lines.
 
 I can handle this by opening the file twice,
 the first time for reading the first line only.
 I suppose there exists a more elegant solution.
 Below is the structure of what I do now.
 Please comment.
 
 f = open(file_name,r)# eerste opening
 file_line  = f.readline()
 special = True if some_condition else False
 f.close()
 
 f = open(file_name,r)# tweede opening
 if not special:
 # use first line, read previously
 stripped_line = file_line.strip()
 else:
 # skip first file_line, or treat in another special way:
 f.next()
 # read other lines:
 for file_line in f:
 stripped_line = file_line.strip()
 # now do something with stripped_line
 f.close()

with open(filename) as lines:
first_line = next(lines, )
if special(first_line):
# ...
else:
lines = itertools.chain([first_line], lines)
for line in lines:
# ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python XML and tables using math

2010-08-16 Thread flebber
On Aug 16, 4:00 pm, Stefan Behnel stefan...@behnel.de wrote:
 flebber, 16.08.2010 05:30:

  I am looking at a project that will import and modify an XML file and
  then export it to a table. Currently a flat file table system should
  be fine.

  I want to export the modified data to the table and then perform a
  handful of maths(largely simple statistical functions) to the data and
  then print out the resultant modified tables.

  I was planning on using Python 2.7 for the project.

  Has anyone used a guide to acheive something similar? I would like to
  read up on it so I can assess my options and best methods, any hints
  or tips?

 That can usually be done in a couple of lines in Python. The approach I
 keep recommending is to use cElementTree (in the stdlib), potentially its
 iterparse() function if the file is too large to easily fit into memory,
 but the code won't change much either way.

 You might want to skip through this list a bit, similar questions have been
 coming up every couple of weeks. The responses often include mostly
 complete implementations that you can borrow from.

 Stefan

okay I found http://effbot.org/zone/celementtree.htm so I will have a
read through there.

I have been creating an every expanding macro/VBA project in Excel and
due to slightly changin source document - the header order changes -
it causes the project to crash out.

I was hoping python and XML may be a bit more robust.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text to DB

2010-08-16 Thread Praveen
On Aug 14, 11:15 am, Dennis Lee Bieber wlfr...@ix.netcom.com wrote:
 On Fri, 13 Aug 2010 09:46:34 -0700 (PDT), Praveen
 praveen.python.pl...@gmail.com declaimed the following in
 gmane.comp.python.general:

  I have a text file in this format
  PRA 1:13 2:20 3:5
  SRA 1:45 2:75 3:9
  TRA 1:2 2:65 3:45

  pattern is- Book Chapter:Verses

  now i have my DB schema like this
  book_id            chapter_id       versed_id

         Off hand, I'd say that's an incomplete schema since there is not
 enough information available to reconstruct the input data...

         I'd say there should be a second relation containing

 book_id book_name



  could any one give me suggestion

         Is there a possibility that a given book name can appear multiple
 times?

 --
         Wulfraed                 Dennis Lee Bieber         AF6VN
         wlfr...@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

f = open(/Users/Trellisys/Desktop//BibleDB/Booktable.txt,r)
bk=[]
cv = []
j=1
d={}
for line in f:
 for l in line.split():
 if l.isalnum():
   bk.append(j)
   j = j+1
 else:
   cv.append(l.split(:))
 '''for i in l.split(:):
   if i.isalpha():
   #print i,j
   j = j+1
   else:
   #print i'''

print bk
print cv
output
[1,2,3] but i am not getting how to map chapterId and versesId with
bookId
Regards,
Praveen
-- 
http://mail.python.org/mailman/listinfo/python-list


Comparing lists

2010-08-16 Thread Francesco Bochicchio
Hi all,

anybody can point me to a description of how the default comparison of
list objects (or other iterables) works?

Apparently l1   l2 is equivalent to  all ( x  y  for  x,y in
zip( l1, l2) ), has is shown in the following tests, but I can't find
it described anywhere:

 [1,2,3]  [1,3,2]
True
 [1,2,3]  [1,2,4]
True
 [1,2,3]  [2,2,3]
True
 [1,2,3]  [0,1,3]
False
 [1,2,3]  [0,2,3]
False
 [1,2,3]  [1,1,3]
False
 [1,2,3]  [1,2,2]
False


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


Problem checking an existing browser cookie

2010-08-16 Thread Νίκος
# initialize cookie
cookie = Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie = cookie.get('visitor')

if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
yandex|13448|spider|crawl)', host ) is None:
blabla...


I checked and Chrome has a cookie names visitor with a value of nikos
within.
So, i have to ask why the if fails?

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


MS Word Document to html conversion

2010-08-16 Thread srinivas hn
Hi,

I am working on application where it requires uploaded document from has to
be converted to the html pages.Am searching for the suitable python package
i dint found any thing apart from word2html.py.But the word2html.py is not
available for download anywhere can any one suggest me how to solve this
problem.


Thanks in advance

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


Re: Comparing lists

2010-08-16 Thread eliasf

On Mon, 16 Aug 2010 13:46:07 +0300, Francesco Bochicchio bieff...@gmail.com 
wrote:


anybody can point me to a description of how the default comparison of
list objects (or other iterables) works?


Sequences of the same type are compared using lexicographical ordering:
http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types
--
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor -- pythonic text-editor

2010-08-16 Thread Steven D'Aprano
On Mon, 16 Aug 2010 01:52:52 -0700, Kruptein wrote:

 I still keep getting more downloads then usual which is awesome, but I
 still don't get any kind of response! 

Welcome to the real world. For every user who sends you an email, you'll 
probably have 1000 who don't. Or 10,000.


 please mail me or reply to this
 post with what you think, You can tell me that the program sucks but if
 you want to, do it in such a way that you also describe what exactly is
 the problem and not just say the total

You've asked for feedback at least three times now. It's probably time to 
stop hassling people. When you have another release ready, then you can 
ask again. Until then, be grateful that people are at least downloading 
it!


 I really need some response because I'm working on version 0.2.1 and I
 want to know what there should be changed/added

If nobody asks for any changes, then just keep doing what you're doing.




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


Re: Python why questions

2010-08-16 Thread Steven D'Aprano
On Mon, 16 Aug 2010 16:28:46 +1200, Lawrence D'Oliveiro wrote:

 In message 8crg0effb...@mid.individual.net, Gregory Ewing wrote:
 
 For example, the constant term of a polynomial is usually called term
 0, not term 1.
 
 That is not some kind of ordinal numbering of the terms, that is the
 power of the variable involved.
 
 And polynomials can have negative powers, too.

Not so. Polynomials, by definition, are limited to non-negative integer 
powers. You're thinking of a polynomial quotient, otherwise known as a 
rational function.

http://mathworld.wolfram.com/Polynomial.html




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


Re: Pop return from stack?

2010-08-16 Thread Steven D'Aprano
On Sun, 15 Aug 2010 21:01:04 -0700, Carey Tilden wrote:

 On Sun, Aug 15, 2010 at 6:43 PM, bvdp b...@mellowood.ca wrote:
 
 Not to belabor the point .. but func is not a standard lib module.
 It's part of a much larger application ... and in that application it
 makes perfect sense to terminate the application if it encounters an
 error. I fail to see the problem with this. Why would an APPLICATION
 raise a error or not exit to the system?
 
 For me, the main reason is to ensure the application has only one exit
 point.  There's only one spot to maintain the code for closing files,
 cleaning up network connections, displaying errors to the user, etc.

You mean all the things that Python's garbage collector already does for 
you?


*wink*



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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Malcolm McLean
On Aug 16, 10:20 am, Standish P stnd...@gmail.com wrote:
 [Q] How far can stack [LIFO] solve do automatic garbage collection and
 prevent memory leak ?

Most programs can be written so that most of their memory allocations
are matched by destructors at the same level.

However the allocations that can't be written this way typically tend
to be the small frequently-called ones used for nodes in dynamic graph
objects, or small resizeable buffers to hold strings and the like.
This is where you get the performance hit with repeated calls to
malloc() and free().

So generally it's not worthwhile writing a stack allocator for a
normal program. That's not to say there aren't a few individual cases
where it can help performance. (See the chapter Memory games in my
book Basic Agorithms for details about memory allocation strategies).


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


Re: Comparing lists

2010-08-16 Thread Peter Otten
Francesco Bochicchio wrote:

 Hi all,
 
 anybody can point me to a description of how the default comparison of
 list objects (or other iterables) works?
 
 Apparently l1   l2 is equivalent to  all ( x  y  for  x,y in
 zip( l1, l2) ), has is shown in the following tests, but I can't find
 it described anywhere:
 
 [1,2,3]  [1,3,2]
 True
 [1,2,3]  [1,2,4]
 True
 [1,2,3]  [2,2,3]
 True
 [1,2,3]  [0,1,3]
 False
 [1,2,3]  [0,2,3]
 False
 [1,2,3]  [1,1,3]
 False
 [1,2,3]  [1,2,2]
 False
 
 
 Ciao
 ---
 FB

Quoting http://docs.python.org/reference/expressions.html


Tuples and lists are compared lexicographically using comparison of 
corresponding elements. This means that to compare equal, each element must 
compare equal and the two sequences must be of the same type and have the 
same length.
If not equal, the sequences are ordered the same as their first differing 
elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). 
If the corresponding element does not exist, the shorter sequence is ordered 
first (for example, [1,2]  [1,2,3]).

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


Re: Python 2.7 re.IGNORECASE broken in re.sub?

2010-08-16 Thread Steven D'Aprano
On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote:

 On Aug 16, 1:07 am, Steven D'Aprano st...@remove-this-
 cybersource.com.au wrote:
 You're passing re.IGNORECASE (which happens to equal 2) as a count
 argument, not as a flag. Try this instead:

  re.sub(rpython\d\d + '(?i)', Python27, t)
 'Python27'
 
 Basically right, but in-line flags must be placed at the start of a
 pattern, or the result is undefined.

Pardon me, but that's clearly not correct, as proven by the fact that the 
above example works.

You can say that the flags *should* go at the start, for the sake of 
efficiency, or ease of comprehension, or tradition, or to appease the 
Regex Cops who roam the streets beating up those who don't write regexes 
in the approved fashion. But it isn't true that they *must* go at the 
front.


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


Re: Python why questions

2010-08-16 Thread Martin Gregorie
On Mon, 16 Aug 2010 12:33:51 +1200, Gregory Ewing wrote:

 Ian Kelly wrote:
 On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie
 mar...@address-in-sig.invalid wrote:
 
   real sample[-500:750];
 
 Ugh, no.  The ability to change the minimum index is evil.
 
 Not always; it can have its uses, particularly when you're using the
 array as a mapping rather than a collection.

Say you have intensity data captured from an X-ray goniometer from 160 
degrees to 30 degrees at 0.01 degree resolution. Which is most evil of 
the following?

1) real intensity[16000:3000]
   for i from lwb intensity to upb intensity
  plot(i/100, intensity[i]);

2) double angle[13000];
   double intensity[13000];
   for (int i = 0; i  13000; i++)
plot(angle[i], intensity[i]);

3) struct 
   { 
  double angle;
  double intensity 
   } measurement;
   measurement m[13000];
   for (int i = 0; i  13000; i++)
plot(m[i].angle, m[i].intensity);

4) double intensity[13000];
   for (int i = 0; i  13000; i++)
  plot((16000 - i)/100, intensity[i])
 
To my mind (1) is much clearer to read and far less error-prone to write, 
while zero-based indexing forces you to use code like (2), (3) or (4), 
all of which obscure rather than clarify what the program is doing.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor -- pythonic text-editor

2010-08-16 Thread Peter Otten
Steven D'Aprano wrote:

 On Mon, 16 Aug 2010 01:52:52 -0700, Kruptein wrote:
 
 I still keep getting more downloads then usual which is awesome, but I
 still don't get any kind of response!
 
 Welcome to the real world. For every user who sends you an email, you'll
 probably have 1000 who don't. Or 10,000.
 
 
 please mail me or reply to this
 post with what you think, You can tell me that the program sucks but if
 you want to, do it in such a way that you also describe what exactly is
 the problem and not just say the total
 
 You've asked for feedback at least three times now. It's probably time to
 stop hassling people. When you have another release ready, then you can
 ask again. Until then, be grateful that people are at least downloading
 it!
 
 
 I really need some response because I'm working on version 0.2.1 and I
 want to know what there should be changed/added
 
 If nobody asks for any changes, then just keep doing what you're doing.

Or you can introduce a bug; if your users don't start complaining you don't 
have any...

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


Re: Problem checking an existing browser cookie

2010-08-16 Thread Peter Otten
Νίκος wrote:

 # initialize cookie
 cookie = Cookie.SimpleCookie()
 cookie.load( os.environ.get('HTTP_COOKIE', '') )
 mycookie = cookie.get('visitor')
 
 if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
 yandex|13448|spider|crawl)', host ) is None:
 blabla...
 
 
 I checked and Chrome has a cookie names visitor with a value of nikos
 within.
 So, i have to ask why the if fails?

Maybe it's because != != ==

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


Re: Python 2.7 re.IGNORECASE broken in re.sub?

2010-08-16 Thread Christopher
On Aug 15, 8:07 pm, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:
 On Sun, 15 Aug 2010 16:45:49 -0700, Christopher wrote:
  I have the following problem:

  t=Python26
  import re
  re.sub(rpython\d\d, Python27, t)
  'Python26'
  re.sub(rpython\d\d, Python27, t, re.IGNORECASE)
  'Python26'
  re.sub(rPython\d\d, Python27, t, re.IGNORECASE)
  'Python27'
  Is this a known bug?  Is it by design for some odd reason?
  help(re.sub)

 Help on function sub in module re:

     sub(pattern, repl, string, count=0)
     ...

 You're passing re.IGNORECASE (which happens to equal 2) as a count
 argument, not as a flag. Try this instead:

  re.sub(rpython\d\d + '(?i)', Python27, t)

 'Python27'


Thanks. Somehow I didn't notice that other argument after looking at
it a million times. :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pop return from stack?

2010-08-16 Thread Steven D'Aprano
On Sun, 15 Aug 2010 18:43:49 -0700, bvdp wrote:

[...]
 However, I have gotten hit with more than one comment like yours. So,
 could you please clarify? Is it bad form to exit an application with
 sys.exit(1) when an error in a file the application is processing is
 found?

My two cents worth... 

The distinction I like to make is between *planned* and *unplanned* 
exits. Planned exits are things like the user choosing Quit from the 
menu, or a command line tool exiting after printing a usage message. 
Exit the application is part of the application's user interface, and 
therefore it is appropriate to exit the application. These aren't errors, 
the exception isn't called SystemError but SystemExit, and it's not 
necessary to print a traceback.

Such exits should usually only exist in the front-end (user-interface) 
code, rarely or never in the back-end.

But *unplanned* exits are errors, and so you should not disguise them as 
planned exits by raising SystemExit, any more than you would disguise 
them as a keyboard interruption by raising KeyboardInterrupt. Raise an 
appropriate exception, and let Python's normal exception-handling code 
clean up and exit for you.

I make one more design choice: if there's an unrecoverable error in user 
input (as opposed unexpectedly bad data or a program bug), I suppress the 
traceback, but any other unrecoverable error, I allow it to print. 
Something vaguely like this:


if __name__ == '__main__':
try:
main()
except getopt.GetoptError, e:
# Unrecoverable error in command line options.
print e.args[0]
sys.exit(42)  # or whatever value is appropriate
except Exception, e:
log_exception(e)  # whatever...
raise


SystemExit won't be caught, and will just exit normally. Any other 
exception won't be caught either, but will lead to a traceback.



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


Re: Dump logging configuration

2010-08-16 Thread Jean-Michel Pichavant

Kxepal wrote:

Hi all!
Sorry for dumb question if it is - I'd tried to google it before but
have found nothing.

Is there any way to dump current logging configuration for future
loading it via fileConfig/dictConfig?
  

I may be wrong but I don't think so.

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


Re: Python why questions

2010-08-16 Thread David Cournapeau
On Mon, Aug 16, 2010 at 9:53 AM, Gregory Ewing
greg.ew...@canterbury.ac.nz wrote:
 On Aug 7, 2010, at 9:14 PM, John Nagle wrote:

  The languages which have real multidimensional arrays, rather
 than arrays of arrays, tend to use 1-based subscripts.  That
 reflects standard practice in mathematics.

 Not always -- mathematicians use whatever starting index is
 most convenient for the problem at hand.

Yes, there are many engineering fields where index starts at 0. Partly
for the reason you have stated concerning polynomials, especially
since this extend to series, which are pervasive in numerical
computing. In linear algebra, though, I remember to have always noted
matrices indexes in the [1,n] range, not [0,n-1]. In general, I
suspect this is much more a tradition than any kind of very reasoned
thinking (and conversely, I find most arguments for 0-indexing and
against one-indexing rather ... unconvincing. What's awkward is when
you have to constantly change from one to the other).

cheers,

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


Textvariable display in label (GUI design)

2010-08-16 Thread Jah_Alarm
hi,

pls help me out with the following issue: I wrote a function that uses
a for loop that changes a value of a certain variable each iteration.
What I want is by clicking a button in GUI (with the command bound to
this function) this value each iteration is displayed in a textbox
(label). So far only one (starting value) is displayed.

thanks,

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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread spinoza1111
On Aug 16, 3:20 pm, Standish P stnd...@gmail.com wrote:
 [Q] How far can stack [LIFO] solve do automatic garbage collection and
 prevent memory leak ?

 Because a stack has push and pop, it is able to release and allocate
 memory. We envisage an exogenous stack which has malloc() associated
 with a push and free() associated with a pop.

 The algorithm using the stack would have to be perfect to prevent
 stack overflow or condition of infinite recursion depth. This would
 involve data type checking to filter out invalid input. The task must
 be casted in an algorithm that uses the stack. Then the algorithm must
 be shown to be heuristically or by its metaphor, to be correct using
 informal reasoning.

 Are there any standard textbooks or papers that show stacks
 implemented in C/C++/Python/Forth with malloc/free in push and pop ?
 If Forth is a general processing language based on stack, is it
 possible to convert any and all algorithms to stack based ones and
 thus avoid memory leaks since a pop automatically releases memory when
 free is an intrinsic part of it.

 KR ANSI has the example of modular programming showing how to
 implement a stack but he uses a fixed length array. It is also
 possibly an endogenous stack. We look for an exogenous stack so that
 element size can vary.

 ===
 Standish P stnd...@gmail.com

Garbage collection doesn't use a stack. It uses a heap, which is in
the abstract a collection of memory blocks of different lengths,
divided into two lists, generally represented as linked lists:

1.  A list of blocks that are free and may be used to store new data

2.  A list of blocks that are in use, or haven't been freed (yet)

There is no way you could do memory management of all but the most
trivial and fixed-length data chunks using a stack. Sure, you could
reserve thousands of bytes on the stack for an array but suppose your
language allows arrays to grow or shrink. To keep its property of
being adjacent, you'd have to do something horrible such as move
unrelated data allocated later, which raises all sorts of security
issues, doesn't it.

A stack, or something which works like a stack (that is, a stack) is a
necessary but not sufficient condition for a working C runtime because
C functions can call themselves recursively, whether directly or
indirectly. If this last condition did not obtain, each function could
give the functions it calls some of its own memory and the called
function could save a fixed set of non-stacked general registers in
that area; this was in fact the practice on IBM 370 and in assembler
language at a time when many data processing managers though
recursion was a Communist plot.

However, data structures of variable size, or data structures that
merely take up a lot of space, don't play nice with others on the
stack, so, we place their address on the stack and store them in
another place, which was named the heap, probably, as a sort of
witticism.

Gilbert and Sullivan:

If anyone anything lacks
He'll find it all ready in stacks

was wrong, and needs to be brought up to date:

You cannot do everything in a stack
Unless you code an almighty hack
If you're a coding Knight who says, Neep,
You'll probably need to implement a heap
A pile a heap of benefits you'll reap
If only my advice in your brain you'll keep
And avoid memory leaks from which data doth seep
By using a well-implemented, well structured, and well-documented
Heap!

[Chorus of Sailors]
We will to heart your advice take, and always use a heap!

[Soloist]
Oh thank you do
To this be true
And always my sage advice do keep
That you always need to use a heap!

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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread spinoza1111
On Aug 16, 7:20 pm, Malcolm McLean malcolm.mcle...@btinternet.com
wrote:
 On Aug 16, 10:20 am, Standish P stnd...@gmail.com wrote: [Q] How far can 
 stack [LIFO] solve do automatic garbage collection and
  prevent memory leak ?

 Most programs can be written so that most of their memory allocations
 are matched by destructors at the same level.

 However the allocations that can't be written this way typically tend
 to be the small frequently-called ones used for nodes in dynamic graph
 objects, or small resizeable buffers to hold strings and the like.
 This is where you get the performance hit with repeated calls to
 malloc() and free().

 So generally it's not worthwhile writing a stack allocator for a
 normal program. That's not to say there aren't a few individual cases
 where it can help performance. (See the chapter Memory games in my
 book Basic Agorithms for details about memory allocation strategies).

Even if it's a troll, it was droll.

In a language that of necessity has a runtime stack or something that
works like a stack (eg., a stack) one finds that the need for explicit
stacks is lessened. For example, in my compiler for [start shameless
plug] Build Your Own .Net Language and Compiler [end shameless plug]
I did not need to use an explicit stack to do recursive descent.

Instead, I simply called finer grained procedures, passing the
compiler state as a parameter, allowing the runtime stack to manage
the return.

To build an explicit stack in this program would have been folly, for
it would have been necessary to either preallocate the stack and thus
legislate the maximum complexity of source code, or use a lot of
memory management in the pre-existing runtime heap.

You didn't tell us you published a book. Can you identify the
publisher?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor -- pythonic text-editor

2010-08-16 Thread eliasf

On Mon, 16 Aug 2010 14:26:09 +0300, Peter Otten __pete...@web.de wrote:

Steven D'Aprano wrote:

If nobody asks for any changes, then just keep doing what you're doing.

Or you can introduce a bug; if your users don't start complaining you don't
have any...


Even that doesn't work. They may blog or tweet about it, complain on foreign 
forums, and set up petitions about it, but they will never, EVER send you an 
email. It's very disheartening.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 re.IGNORECASE broken in re.sub?

2010-08-16 Thread Alex Willmer
On Aug 16, 12:23 pm, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:
 On Sun, 15 Aug 2010 17:36:07 -0700, Alex Willmer wrote:
  On Aug 16, 1:07 am, Steven D'Aprano st...@remove-this-
  cybersource.com.au wrote:
  You're passing re.IGNORECASE (which happens to equal 2) as a count
  argument, not as a flag. Try this instead:

   re.sub(rpython\d\d + '(?i)', Python27, t)
  'Python27'

  Basically right, but in-line flags must be placed at the start of a
  pattern, or the result is undefined.

 Pardon me, but that's clearly not correct, as proven by the fact that the
 above example works.

Undefined includes 'might work sometimes'. I refer you to the Python
documentation:

Note that the (?x) flag changes how the expression is parsed. It
should be used first in the expression string, or after one or more
whitespace characters. If there are non-whitespace characters before
the flag, the results are undefined.
http://docs.python.org/library/re.html#regular-expression-syntax

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


Re: Python why questions

2010-08-16 Thread Neil Cerutti
On 2010-08-15, John Nagle na...@animats.com wrote:
 In retrospect, C's pointer=array concept was a terrible
 mistake.

C arrays are not pointers.

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


Re: Python 2.7 re.IGNORECASE broken in re.sub?

2010-08-16 Thread Alex Willmer
On Aug 16, 1:46 pm, Alex Willmer a...@moreati.org.uk wrote:
 Note that the (?x) flag changes how the expression is parsed. It
 should be used first in the expression string, or after one or more
 whitespace characters. If there are non-whitespace characters before
 the flag, the results are undefined.
 http://docs.python.org/library/re.html#regular-expression-syntax

Hmm, I found a lot of instances that place (?iLmsux) after non-
whitespace characters

http://google.com/codesearch?hl=enlr=q=file:\.py[w]%3F$+[^[:space:]%22']%2B\(\%3F[iLmsux]%2B\)

including two from the Python unit tests, re_test.py lines 109-110.
Perhaps the documentation is overly cautious..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python Sandbox

2010-08-16 Thread Roland Koebler
On Sat, Aug 14, 2010 at 07:54:11PM -0700, Stephen Hansen wrote:
 How are you implementing refusing-names-beginning-with-underscore, out
 of curiosity?
I compile the expressions and look into co_names, e.g.:
   expr = 0 .__class__
   c=compile(expr,,eval)
   c.co_names
  ('__class__',)


regards,
Roland

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


About UpdateLayeredWindow

2010-08-16 Thread Alexandru Ionescu
Hello,

In the last two weeks I've been trying to properly use UpdateLayeredWindow in 
Python but I'm only getting errors. I searched a lot on the internet and you 
are 
the only person who posted about using ULW in Python. I tried with ctypes and I 
also tried with win32gui  win32api. I got all kinds of errors. In the end I 
got 
to error code 5 (ERROR_ACCESS_DENIED) and nothing appears on the screen.
Please send me a small working example in Python of UpdateLayeredWindow, either 
using ctypes or win32gui  win32api.
My email address is q_cr...@yahoo.com

Thank you,
Alex


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


passing variables as object attributes

2010-08-16 Thread Vikas Mahajan
Hello to all

I am new to python. I am facing problem to use variables as object
attributes. I have to use loop and dynamically add attributes to a
object and for this purpose I have to use variables with object names.

For example-:
Let us say object car has an attribute engine, then
varname = engine
car.varname = dummy value
is giving me Error: object car does not have attribute varname.

Please tell me how can I use variables as objects attributes.

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


Re: passing variables as object attributes

2010-08-16 Thread Nitin Pawar
you would need to define a class first with its attiributes and then you may
want to initiate the variables by calling the class initilializer

On Mon, Aug 16, 2010 at 7:10 PM, Vikas Mahajan vikas.mahaja...@gmail.comwrote:

 Hello to all

 I am new to python. I am facing problem to use variables as object
 attributes. I have to use loop and dynamically add attributes to a
 object and for this purpose I have to use variables with object names.

 For example-:
 Let us say object car has an attribute engine, then
 varname = engine
 car.varname = dummy value
 is giving me Error: object car does not have attribute varname.

 Please tell me how can I use variables as objects attributes.

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




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


Re: When the first line of a file tells something about the other lines

2010-08-16 Thread egbert
On Mon, Aug 16, 2010 at 11:59:57AM +0200, Peter Otten wrote:
 
 with open(filename) as lines:
 first_line = next(lines, )
 if special(first_line):
 # ...
 else:
 lines = itertools.chain([first_line], lines)
 for line in lines:
 # ...

Beautiful. And a nice suggestion to read the itertools docs.
egbert
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Re: passing variables as object attributes

2010-08-16 Thread Vikas Mahajan
On 16 August 2010 19:23, Nitin Pawar nitinpawar...@gmail.com wrote:
 you would need to define a class first with its attiributes and then you may
 want to initiate the variables by calling the class initilializer

Actually I have to dynamically add attributes to a object. I am
writing python script for  FreeCAD software. I am using loop to create
multiple cylinders and I am writing following code-:
cyname = Cylinder
FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
FreeCAD.ActiveDocument.cyname.Radius= .5
FreeCAD.ActiveDocument.cyname.Height= 10

And I am getting this error-:
AttributeError: 'App.Document' object has no attribute 'cyname'

But when I use Cylinder in place of cyname, I am not getting any error.

Please help.

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


does someone has a binary 32-bit windows installer for arac ?

2010-08-16 Thread Stef Mientki
 thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing variables as object attributes

2010-08-16 Thread nn
On Aug 16, 10:08 am, Vikas Mahajan vikas.mahaja...@gmail.com wrote:
 On 16 August 2010 19:23, Nitin Pawar nitinpawar...@gmail.com wrote: you 
 would need to define a class first with its attiributes and then you may
  want to initiate the variables by calling the class initilializer

 Actually I have to dynamically add attributes to a object. I am
 writing python script for  FreeCAD software. I am using loop to create
 multiple cylinders and I am writing following code-:
 cyname = Cylinder
 FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
 FreeCAD.ActiveDocument.cyname.Radius= .5
 FreeCAD.ActiveDocument.cyname.Height= 10

 And I am getting this error-:
 AttributeError: 'App.Document' object has no attribute 'cyname'

 But when I use Cylinder in place of cyname, I am not getting any error.

 Please help.

 Thanks.

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


Re: passing variables as object attributes

2010-08-16 Thread nn
On Aug 16, 10:08 am, Vikas Mahajan vikas.mahaja...@gmail.com wrote:
 On 16 August 2010 19:23, Nitin Pawar nitinpawar...@gmail.com wrote: you 
 would need to define a class first with its attiributes and then you may
  want to initiate the variables by calling the class initilializer

 Actually I have to dynamically add attributes to a object. I am
 writing python script for  FreeCAD software. I am using loop to create
 multiple cylinders and I am writing following code-:
 cyname = Cylinder
 FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
 FreeCAD.ActiveDocument.cyname.Radius= .5
 FreeCAD.ActiveDocument.cyname.Height= 10

 And I am getting this error-:
 AttributeError: 'App.Document' object has no attribute 'cyname'

 But when I use Cylinder in place of cyname, I am not getting any error.

 Please help.

 Thanks.

This might work:
cyname = Cylinder
FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
getattr(FreeCAD.ActiveDocument,cyname).Radius= .5
getattr(FreeCAD.ActiveDocument,cyname).Height= 10

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


how to switch image in tkinter? making it mutable? how?

2010-08-16 Thread ChrisChia
I have this:
image1 = ImageTk.PhotoImage(file = c:\\f1.jpg)
image2 = ImageTk.PhotoImage(file = c:\\f2.jpg)

imagelist.append(image1)
imagelist.append(image2)

self.label  = tk.Label(image = imagelist[0])

is there a way that i can create a method to switch the display the
image2 (imagelist 2nd element)
without using label.bind?

can i make an image mutable?


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


Re: Dump logging configuration

2010-08-16 Thread Jean-Michel Pichavant

Jean-Michel Pichavant wrote:

Kxepal wrote:

Hi all!
Sorry for dumb question if it is - I'd tried to google it before but
have found nothing.

Is there any way to dump current logging configuration for future
loading it via fileConfig/dictConfig?
  

I may be wrong but I don't think so.

JM
Please understand that I don't think such feature exists (to oppose to 
thinking that I'm not wrong :o) )


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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread jacko
 is it possible to convert any and all algorithms to stack based ones and thus 
 avoid memory leaks?

No, not really. If you keep the allocated things and free them in
reverse order on exit, then well yes, but practically, early free()
frees memory for reuse on low memory systems. In this sense not
'reversed' out of order free is essential in some contexts.

The question then becomes what is the best heap fragmentation/
compaction strategy and what is the best allocation algorithm to
allocate addresses?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-16 Thread Ian Kelly
On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries downa...@gmail.com wrote:
 I suspect that there exists a largest unpurchasable quantity iff at
 least two of the pack quantities are relatively prime, but I have made
 no attempt to prove this.

 That for sure is not correct; packs of 2, 4 and 7 do have a largest
 unpurchasable quantity.

2 and 7 are relatively prime, so this example fits my hypothesis.

 I'm pretty sure that if there's no common divisor for all three (or more)
 packages (except one), there is a largest unpurchasable quantity. That is: ∀
 i1: ¬(i|a) ∨ ¬(i|b) ∨ ¬(i|c), where ¬(x|y) means x is no divider of y

No.  If you take the (2,4,7) example and add another pack size of 14,
it does not cause quantities that were previously purchasable to
become unpurchasable.

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


question about pdb assignment statements

2010-08-16 Thread Steve Ferg
In this little script:

 pre
 import pdb
 pdb.set_trace()
 def main():
 xm = 123
 print(Hello,world!)
 main()
 /pre

When I run this, I use pdb to step through it until I reach the point
in main() where the xm variable has been initialized, and then I try
to use pdb to reset the value of xm, and I can't.

Does anybody know why?

As I understand the documentation,  http://docs.python.org/library/pdb.html
I *should* be able to do this.

 [!]statement
 Execute the (one-line) statement in the context of the current stack
frame.

Is there something about in the context of the current stack frame
that I don't understand?  Or is it a bug (or a limitation) in pdb?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to switch image in tkinter? making it mutable? how?

2010-08-16 Thread Eric Brunel
In article 
414ff6dd-73ef-48df-bd2b-080a2c710...@h17g2000pri.googlegroups.com,
 ChrisChia chrischi...@gmail.com wrote:

 I have this:
 image1 = ImageTk.PhotoImage(file = c:\\f1.jpg)
 image2 = ImageTk.PhotoImage(file = c:\\f2.jpg)
 
 imagelist.append(image1)
 imagelist.append(image2)
 
 self.label  = tk.Label(image = imagelist[0])
 
 is there a way that i can create a method to switch the display the
 image2 (imagelist 2nd element)
 without using label.bind?
 
 can i make an image mutable?

Unfortunately, I don't know the package ImageTk you're using. But at tk 
level, images are mutable without problem. It seems however that the tcl 
commands allowing to read an existing image from a file are not exposed 
at Tkinter level. But it is still possible to send the command to the 
underlying tcl interpreter to do it:

from Tkinter import *
root = Tk()
image = PhotoImage(file='f1.gif')
label = Label(root, image=image)
## When you want to change the image:
root.tk.call(image, 'read', 'f2.gif', '-shrink')

This will only work with image formats supported in the tcl/tk core, 
which are basically only GIF so far.

BTW, I don't understand why you talk about label.bindŠ If you need to do 
anything when the label is clicked, you have to make a binding on the 
label whatever it is.

HTH anyway.
 - Eric -
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Malcolm McLean
On Aug 16, 3:14 pm, spinoza spinoza1...@yahoo.com wrote:

 To build an explicit stack in this program would have been folly, for
 it would have been necessary to either preallocate the stack and thus
 legislate the maximum complexity of source code, or use a lot of
 memory management in the pre-existing runtime heap.

The problem is that if you reallocate the stack, you invalidate all
pointers to objects on it. So you have to use handles instead. At
which point you might as well admit that you are no longer programming
in C.


 You didn't tell us you published a book. Can you identify the
 publisher?- Hide quoted text -

It's a print on demand, by Lulu. O'Reilley said they liked it but they
couldn't sell books on C. (I've an open invitation to write a computer
book for them in another language).

I don't really recommend print on demand. The nice thing is that you
can sell the book for about half the price it would cost under a
traditional publishing model. The problem is that people still use
acceptance by a traditional publisher as a filter.


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


Re: Textvariable display in label (GUI design)

2010-08-16 Thread Eric Brunel
In article 
993d9560-564d-47f0-b2db-6f0c6404a...@g6g2000pro.googlegroups.com,
 Jah_Alarm jah.al...@gmail.com wrote:

 hi,
 
 pls help me out with the following issue: I wrote a function that uses
 a for loop that changes a value of a certain variable each iteration.
 What I want is by clicking a button in GUI (with the command bound to
 this function) this value each iteration is displayed in a textbox
 (label). So far only one (starting value) is displayed.
 
 thanks,
 
 Alex

First, with posts like this, you're highly unlikely to get any useful 
answer: please strip down your code to the smallest part that displays 
the problem, post this code here, explaining what you're expecting and 
what you're getting. Otherwise, people just won't know what you're 
talking about unless they have a crystal ballŠ

Now using my own crystal ball: if you don't return the control to the 
GUI each time your variable is increased, the GUI won't get a chance to 
update itself. Since you seem to use Tkinter (another wild guessŠ), you 
probably need a call to the update_idletasks method on any Tkinter 
widget each time you change your TextVariable.

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


Re: passing variables as object attributes

2010-08-16 Thread misterdi
On Aug 16, 8:40 pm, Vikas Mahajan vikas.mahaja...@gmail.com wrote:
 Hello to all

 I am new to python. I am facing problem to use variables as object
 attributes. I have to use loop and dynamically add attributes to a
 object and for this purpose I have to use variables with object names.

 For example-:
 Let us say object car has an attribute engine, then
 varname = engine
 car.varname = dummy value
 is giving me Error: object car does not have attribute varname.

 Please tell me how can I use variables as objects attributes.

 Thanks.

I'm not a python expert, so this may not be accurate
For me it is easier to define a class that represent the object, and
then set attribute for the object.

for example :
# define a class with no attribute
class Car():
pass

# instance the class
mycar = Car()
# dynamically set attribute to the instance
newattr = engine
setattr(mycar, newattr, dummy value)
# or dynamically set attribute to the Class so every instance will
inherit it
classattr = color
setattr(mycar, classattr, yellow)

But as I mention, I'm not an expert so maybe it's not a pythonic way
to add attribute to an object.

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-16 Thread Ian Kelly
On Mon, Aug 16, 2010 at 11:04 AM, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries downa...@gmail.com wrote:
 I suspect that there exists a largest unpurchasable quantity iff at
 least two of the pack quantities are relatively prime, but I have made
 no attempt to prove this.

 That for sure is not correct; packs of 2, 4 and 7 do have a largest
 unpurchasable quantity.

 2 and 7 are relatively prime, so this example fits my hypothesis.

Although now that I think about it some more, there are
counter-examples.  For example, the pack sizes (6, 10, 15) have a
largest unpurchasable quantity of 29, but no two of those are
relatively prime.

I'm going to revise my hypothesis to state that a largest
unpurchasable quantity exists iff some there exists some relatively
prime subset of the pack sizes of cardinality 2 or greater.

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dump logging configuration

2010-08-16 Thread Kxepal
On Aug 16, 6:53 pm, Jean-Michel Pichavant jeanmic...@sequans.com
wrote:
 Jean-Michel Pichavant wrote:
  Kxepal wrote:
  Hi all!
  Sorry for dumb question if it is - I'd tried to google it before but
  have found nothing.

  Is there any way todumpcurrentloggingconfiguration for future
  loading it via fileConfig/dictConfig?

  I may be wrong but I don't think so.

  JM

 Please understand that I don't think such feature exists (to oppose to
 thinking that I'm not wrong :o) )

 JM

Ah, you have break my dream, but thanks(: It's a pity, because it very
handy feature, but now I see a lot of problems to implement it with
current logging flexibility.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor -- pythonic text-editor

2010-08-16 Thread Kruptein
on steven, peter and eliasf:

Well okay I'm new to the world of developing programs, if I encounter
problems I directly post a bug on the relevant page, that's maybe why
I was a bit frustrated :)

but what you three say is indeed true..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pop return from stack?

2010-08-16 Thread Carey Tilden
On Mon, Aug 16, 2010 at 4:18 AM, Steven D'Aprano
st...@remove-this-cybersource.com.au wrote:

 On Sun, 15 Aug 2010 21:01:04 -0700, Carey Tilden wrote:

 On Sun, Aug 15, 2010 at 6:43 PM, bvdp b...@mellowood.ca wrote:

 Not to belabor the point .. but func is not a standard lib module.
 It's part of a much larger application ... and in that application it
 makes perfect sense to terminate the application if it encounters an
 error. I fail to see the problem with this. Why would an APPLICATION
 raise a error or not exit to the system?

 For me, the main reason is to ensure the application has only one exit
 point.  There's only one spot to maintain the code for closing files,
 cleaning up network connections, displaying errors to the user, etc.

 You mean all the things that Python's garbage collector already does for
 you?

Are you actually disagreeing with the point or just poking fun at my
examples?  If the former, well, phooey.  If the latter, c'est la vie.

 *wink*

:-P

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


Re: passing variables as object attributes

2010-08-16 Thread Jean-Michel Pichavant

Vikas Mahajan wrote:

On 16 August 2010 19:23, Nitin Pawar nitinpawar...@gmail.com wrote:
  

you would need to define a class first with its attiributes and then you may
want to initiate the variables by calling the class initilializer



Actually I have to dynamically add attributes to a object. I am
writing python script for  FreeCAD software. I am using loop to create
multiple cylinders and I am writing following code-:
cyname = Cylinder
FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
FreeCAD.ActiveDocument.cyname.Radius= .5
FreeCAD.ActiveDocument.cyname.Height= 10

And I am getting this error-:
AttributeError: 'App.Document' object has no attribute 'cyname'

But when I use Cylinder in place of cyname, I am not getting any error.

Please help.

Thanks.
  

obj.attribute = 5 = setattr(obj, attribute, 5)

obj.attribute = getattr(obj, attribute)

So considering your example,

getattr(FreeCAD.ActiveDocument, cyname).Radius = .5

should do the trick.

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


Re: Opposite of split

2010-08-16 Thread Alex van der Spek

Thanks much,

Nope, no homework. This was a serious question from a serious but perhaps 
simple physicist who grew up with Algol, FORTRAN and Pascal, taught himself 
VB(A) and is looking for a replacement of VB and finding that in Python. You 
can guess my age now.


Most of my work I do in R nowadays but R is not flexible enough for some 
file manipulation operations. I use the book by Lutz (Learning Python). 
The join method for strings is in there. I did not have the book at hand and 
I was jetlagged too. I do apologize for asking a simple question.


I had no idea that some would go to the extent of giving trick solutions for 
simple, supposedly homework questions. Bear in mind Python is a very feature 
rich language. You cannot expect all newbies to remember everything.


By the way, I had a working program that did what I wanted using still 
simpler string concatenation. Replaced that now by tab.join([lines[i][k][2] 
for i in range(5)]), k being a loop counter. Judge for yourself. That is the 
level I am at after 6 weeks of doing excercises from my programming book on 
Pascal in Python.
Thanks for the help. I do hope there is no entry level for using this group. 
If there is, I won't meet it for a while.

Alex van der Spek

D'Arcy J.M. Cain da...@druid.net wrote in message 
news:mailman.2159.1281917130.1673.python-l...@python.org...

On 15 Aug 2010 23:33:10 GMT
Steven D'Aprano st...@remove-this-cybersource.com.au wrote:
Under what possible circumstances would you prefer this code to the 
built-

in str.join method?


I assumed that it was a trap for someone asking for us to do his
homework.  I also thought that it was a waste of time because I knew
that twenty people would jump in with the correct answer because of
finally, one that I can answer syndrome.

--
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner. 


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


EOFError with fileinput

2010-08-16 Thread Alex van der Spek

Using the fileinput module to process lists of files:


for line in fileinput.input(logs):


Unfortunately, EOFError does not seem to indicate the end-of-file condition 
correctly when using fileinput.


How would you find the EOF file for all the files in the file list 'logs'?

Thank you,
Alex van der Spek 


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


Re: python strings and {} in Tkinter entry widgets

2010-08-16 Thread Jeff Hobbs
On Aug 15, 4:41 pm, Chris Hare ch...@labr.net wrote:
 I have some code that pulls a value from a database.  In this case, it is 
 three space delimited words.  When I display the value in a Tkinter.Entry 
 widget, the text has curly braces around it, even when there are none in the 
 surrounding the text in the database.

 Is this normal, and how do I prevent it or remove them correctly before 
 displaying the text in the Entry widget?

Python ['', '', ''] == Tcl {{} {} {}}
Python 'a word' == Tcl {a word}

You are getting a literal translation occurring, and you need to split/
join or index the items properly.  Without being more clear how you
want to represent your data, what you need isn't clear.  Perhaps you
just need to reference the first index of the variable, or ... who
knows, there are lots of possibilities.

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-16 Thread Roald de Vries

On Aug 16, 2010, at 5:04 PM, Ian Kelly wrote:
On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries downa...@gmail.com  
wrote:

I suspect that there exists a largest unpurchasable quantity iff at
least two of the pack quantities are relatively prime, but I have  
made

no attempt to prove this.


That for sure is not correct; packs of 2, 4 and 7 do have a largest
unpurchasable quantity.


2 and 7 are relatively prime, so this example fits my hypothesis.


I now notice I misread your post (as 'iff the least two pack  
quantities are relatively prime')


I'm pretty sure that if there's no common divisor for all three (or  
more)
packages (except one), there is a largest unpurchasable quantity.  
That is: ∀
i1: ¬(i|a) ∨ ¬(i|b) ∨ ¬(i|c), where ¬(x|y) means x is no  
divider of y


No.  If you take the (2,4,7) example and add another pack size of 14,
it does not cause quantities that were previously purchasable to
become unpurchasable.


Then what is the common divisor of 2, 4, 7 and 14? Not 2 because ¬(2| 
7), not anything higher than 2 because that's no divisor of 2.


Cheers, Roald
--
http://mail.python.org/mailman/listinfo/python-list


Re: Opposite of split

2010-08-16 Thread Alex van der Spek
Perhaps the ones here who think I was trying to make you do my homework can 
actually help me for real. Since I run my own company (not working for any 
of the big ones) I can't afford official training in anything. So I teach 
myself, help is always welcome and sought for. If that feels like doing 
homework for me, so be it.


The fact is that I do try to learn Python. It can do things I thought 
required much more coding. Look at the attached. It builds a concordance 
table first. That was an excercise from a book on Pascal programming. In 
Pascal the solution is 2 pages of code. In Python it is 8 lines. Beautiful!


Anybody catches any other ways to improve my program (attached), you are 
most welcome. Help me learn, that is one of the objectives of this 
newsgroup, right? Or is it all about exchanging the next to impossible 
solution to the never to happen unreal world problems?


Regards,
Alex van der Spek


D'Arcy J.M. Cain da...@druid.net wrote in message 
news:mailman.2159.1281917130.1673.python-l...@python.org...

On 15 Aug 2010 23:33:10 GMT
Steven D'Aprano st...@remove-this-cybersource.com.au wrote:
Under what possible circumstances would you prefer this code to the 
built-

in str.join method?


I assumed that it was a trap for someone asking for us to do his
homework.  I also thought that it was a waste of time because I knew
that twenty people would jump in with the correct answer because of
finally, one that I can answer syndrome.

--
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner. 

#! usr/bin/env python
# Merge log files to autolog file
import os
import fileinput
#top='C:\\Documents and Settings\\avanderspek\\My 
Documents\\CiDRAdata\\Syncrude\\CSL\\August2010'
top='C:\\Users\\ZDoor\\Documents\\CiDRA\\Syncrude\CSL\\August2010'
i,j,k=0,0,0
date={}

fps=0.3048
tab='\t'

bt='-999.25'+'\t''-999.25'+'\t''-999.25'+'\t''-999.25'+'\t'+'-999.25'
al='Status'+'\t'+'State'+'\t'+'-999.25'

for root,dirs,files in os.walk(top):
   #Build a concordance table of days on which data was collected
   for name in files:
   ext=name.split('.',1)[1]
   if ext=='txt':
   dat=name.split('_')[1].split('y')[1]
   if dat in date.keys():
   date[dat]+=1
   else:
   date[dat]=1
   print 'Concordance table of days:'
   print date
   print 'List of files processed:'
   #Build a list of same day filenames, 5 max for a profile meter,skip first 
and last days
   for f in sorted(date.keys())[2:-1]:
   logs=[]
   for name in files:
   ext=name.split('.')[1]
   if ext=='txt':
   dat=name.split('_')[1].split('y')[1]
   if dat==f:
   logs.append(os.path.join(root,name))
   #Open the files and read line by line
   datsec=False
   lines=[[] for i in range(5)]
   fn=0
   for line in fileinput.input(logs):
   if line.split()[0]=='DataID':
   datsec=True
   ln=0
   if datsec:
   lines[fn].append(line.split())
   ln+=1
   if ln==10255:
   datsec=False
   fileinput.nextfile()
   fn+=1
   print fileinput.filename().rsplit('\\',1)[1]
   fileinput.close()
   aut='000_AutoLog'+f+'.log'
   out=os.path.join(root,aut)
   alf=open(out,'w')
   alf.write('Timestamp (mm/dd/ hh:mm:ss)   VF 1VF 2VF 3
VF 4VF 5Q 1 Q 2 Q 3 Q 4 Q 5 Status  State   Metric  
Band Temperature 1  Band Temperature 2  Band Temperature 3  Band 
Temperature 4  Band Temperature 5  SPL 1   SPL 2   SPL 3   SPL 4   SPL 
5'+'\n')
   for wn in range(1,10255,1):
   for i in range(5):
   lines[i][wn][2]=str(float(lines[i][wn][2])/fps)
   tp=lines[0][wn][0]+' '+lines[0][wn][1]
   vf=tab.join([lines[i][wn][2] for i in range(5)])
   vq=tab.join([lines[i][wn][3] for i in range(5)])

   vs=tab.join([lines[i][wn][4] for i in range(5)])
   #sf=tab.join([lines[i][wn][5] for i in range(5)])
   #sq=tab.join([lines[i][wn][6] for i in range(5)])
   #ss=tab.join([lines[i][wn][7] for i in range(5)])
   alf.write(tp+'\t'+vf+'\t'+vq+'\t'+al+'\t'+bt+'\t'+vs+'\n')
   alf.close()
print Done

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


Newbie: strftime object error message

2010-08-16 Thread fuglyducky
I am trying to call a function with a couple additional parameters.
Unfortunately, for whatever reason I am unable to get this to work. I
am assuming that line is not passing correctly but I don't understand
why???

I can't share all of the code because it has IP in it but below are
the pertinent snippets.

Thanks in advance!

##

PY: 3.1.2


FUNCTION CALL:
text_file = open(file_name, r)
for line in text_file:
new_foo = pop_time(current_time, line)
# current_time = datetime.datetime.now()


FUNCTION:
def pop_time(line, cur_time):
global new_string
global current_time


# Generate random time between 0 and 30 seconds
# Changes the time delta every time function is run
rand_time = random.randint(0, 30)
delta_time = datetime.timedelta(seconds=rand_time)

# Sets the time format for string output
format_time = cur_time.strftime(%Y-%m-%d %H:%M:%S)


ERROR MSG:
format_time = cur_time.strftime(%Y-%m-%d %H:%M:%S)
AttributeError: 'str' object has no attribute 'strftime'


NOTE: current_time prints within the function, line does not
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EOFError with fileinput

2010-08-16 Thread Mark Lawrence

On 16/08/2010 17:29, Alex van der Spek wrote:

Using the fileinput module to process lists of files:


for line in fileinput.input(logs):


Unfortunately, EOFError does not seem to indicate the end-of-file
condition correctly when using fileinput.

How would you find the EOF file for all the files in the file list 'logs'?

Thank you,
Alex van der Spek


I'm not sure exactly what you're asking here.  Could you a brief 
description as to what you're trying to achieve, then put the question 
again.


Cheers.

Mark Lawrence.

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


Re: how to switch image in tkinter? making it mutable? how?

2010-08-16 Thread Jeff Hobbs
On Aug 16, 7:30 am, ChrisChia chrischi...@gmail.com wrote:
 I have this:
 image1 = ImageTk.PhotoImage(file = c:\\f1.jpg)
 image2 = ImageTk.PhotoImage(file = c:\\f2.jpg)

 imagelist.append(image1)
 imagelist.append(image2)

 self.label  = tk.Label(image = imagelist[0])

 is there a way that i can create a method to switch the display the
 image2 (imagelist 2nd element)
 without using label.bind?

 can i make an image mutable?

self.label.configure(image = imagelist[1]) will change the image
displayed.
With PIL images, you can use image1.fromstring(...) that should have a
similar effect, in that it changes the underlying image data and the
label will display that.

Whether you need to label.bind or something else to effect this change
is up to you.  You could have it happen on a timer, triggered by an
event, or randomly effected by solar flares, depending on your
application's needs.

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


Re: Opposite of split

2010-08-16 Thread D'Arcy J.M. Cain
On Mon, 16 Aug 2010 18:26:46 +0200
Alex van der Spek zd...@xs4all.nl wrote:
 Nope, no homework. This was a serious question from a serious but perhaps 
 simple physicist who grew up with Algol, FORTRAN and Pascal, taught himself 
 VB(A) and is looking for a replacement of VB and finding that in Python. You 
 can guess my age now.
 
 Most of my work I do in R nowadays but R is not flexible enough for some 
 file manipulation operations. I use the book by Lutz (Learning Python). 
 The join method for strings is in there. I did not have the book at hand and 
 I was jetlagged too. I do apologize for asking a simple question.

I'm not actually the one that presented the convuluted example.  I
think the one who did just felt that someone had a question and they
were passing it to the group instead of doing a simple Google search.
The solution he posted looked like something designed to make the
teacher scratch his head and ask embarrassing questions of the student.

 Thanks for the help. I do hope there is no entry level for using this group. 
 If there is, I won't meet it for a while.

I think that the only thing people expect is that you do a quick search
first and show that you have tried first.  Some questions have been
asked and answered so many times that a search of the archives finds
what you want without waiting for an answer.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing variables as object attributes

2010-08-16 Thread Vikas Mahajan
@All
Thanks a lot.
getattr and setattr functions solved my problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to convert bytearray into integer?

2010-08-16 Thread Jacky
Hi there,

Recently I'm facing a problem to convert 4 bytes on an bytearray into
an 32-bit integer.  So far as I can see, there're 3 ways: a) using
struct module, b) using ctypes module, and c) manually manipulation.

Are there any other ways?

My sample is as following:

-
import struct
import ctypes

def test_struct(buf, offset):
  return struct.unpack_from(I, buf, offset)[0]

def test_ctypes(buf, offset):
  return ctypes.c_uint32.from_buffer(buf, offset).value

def test_multi(buf, offset):
  return buf[offset] + (buf[offset+1]  8) + (buf[offset+2]  16) +
(buf[offset+3]  24)

buf_w = bytearray(5)
buf_w[1] = 1
buf_r = buffer(buf_w)

if __name__ == '__main__':
  import timeit

  t1 = timeit.Timer(test_struct(buf_r, 1),
from __main__ import test_struct, buf_r)
  t2 = timeit.Timer(test_ctypes(buf_w, 1),
from __main__ import test_ctypes, buf_w)
  t3 = timeit.Timer(test_multi(buf_w, 1),
from __main__ import test_multi, buf_w)
  print t1.timeit(number=1000)
  print t2.timeit(number=1000)
  print t3.timeit(number=1000)
-

Yet the results are bit confusing:

-
number = 1
0.0081958770752
0.012549161911
0.0112121105194

number = 1000
0.00087308883667
0.00125789642334
0.00110197067261

number = 100
0.917911529541 # 9.17911529541e-05
0.000133991241455
0.00011420249939

number = 10
1.69277191162e-05
2.19345092773e-05
1.69277191162e-05

number = 1
1.00135803223e-05
1.00135803223e-05
5.96046447754e-06
-

As the number of benchmarking loops decreasing, method c which is
manually manipulating overwhelms the former 2 methods.  However, if
number == 10K, the struct method wins.

Why does it happen?

Thanks,
Jacky (jacky.chao.wang#gmail.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python strings and {} in Tkinter entry widgets

2010-08-16 Thread Chris Hare

On Aug 16, 2010, at 11:40 AM, Jeff Hobbs wrote:

 On Aug 15, 4:41 pm, Chris Hare ch...@labr.net wrote:
 I have some code that pulls a value from a database.  In this case, it is 
 three space delimited words.  When I display the value in a Tkinter.Entry 
 widget, the text has curly braces around it, even when there are none in the 
 surrounding the text in the database.
 
 Is this normal, and how do I prevent it or remove them correctly before 
 displaying the text in the Entry widget?
 
 Python ['', '', ''] == Tcl {{} {} {}}
 Python 'a word' == Tcl {a word}
 
 You are getting a literal translation occurring, and you need to split/
 join or index the items properly.  Without being more clear how you
 want to represent your data, what you need isn't clear.  Perhaps you
 just need to reference the first index of the variable, or ... who
 knows, there are lots of possibilities.
 
 Jeff
 -- 
 http://mail.python.org/mailman/listinfo/python-list

Actually I want all of the words, as they form the name of an organization 
entered by the user.  So the space delimited words should be displayed without 
the {} in the tkinker entry box.  The contents of the widget is a persons first 
and last name, space delimited
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Opposite of split

2010-08-16 Thread D'Arcy J.M. Cain
On Mon, 16 Aug 2010 18:44:08 +0200
Alex van der Spek zd...@xs4all.nl wrote:
 Perhaps the ones here who think I was trying to make you do my homework can 

You keep replying to my message but as I pointed out in my previous
message, I'm not the one who thought that you posted a homework
question.  I'm the one who thought that the other poster thought that
you posted a homework question.  Honestly, while I thought it was a
question that could have been answered faster with a Google search, it
did not look like a homework question to me.

 actually help me for real. Since I run my own company (not working for any 
 of the big ones) I can't afford official training in anything. So I teach 
 myself, help is always welcome and sought for. If that feels like doing 
 homework for me, so be it.

Well, it is home work but there is nothing wrong with asking for help
anyway.  When people complain about homework questions it is generally
because someone has posted the question verbatim from the assignment
and asks for a complete solution.  That's annoying.  What you have done
here is good because you show some work and ask for help with it.
Slightly better would be to ask specific questions about areas that you
are struggling with but this is good.

 The fact is that I do try to learn Python. It can do things I thought 
 required much more coding. Look at the attached. It builds a concordance 
 table first. That was an excercise from a book on Pascal programming. In 
 Pascal the solution is 2 pages of code. In Python it is 8 lines. Beautiful!

I guess the real entry level test here is that you have to be smart
enough to choose Python since it is the best language.  You pass.  :-)

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


How can I bundle a PyGTK program in windows so my users don't need to install Python or the GTK+ libs?

2010-08-16 Thread Waspinator
I found this question on 
http://faq.pygtk.org/index.py?file=faq21.005.htpreq=show
but the answer did not help me.

For example I have a simple program below that I would like to
'compile' with py2exe (or anything else if it's simpler) to run in
windows as a single bundled executable file with no installation (no
INNO setup), and no requirements for gtk or python installations. I
doesn't matter if the .exe file is 30 MB to only display a hello world
app, as long as it works. (although the smaller the better)

The application already works in my windows test environment because I
have installed python 2.6 with pygtk and a gtk bundle.

Can someone please provide some simple and clear instructions on how I
can do this?

Thanks,

Waspinator

simple.py
---
  import gtk

  window = gtk.Window()
  window.set_title(PyGTK Test Window)
  window.connect(destroy, gtk.main_quit)
  window.show_all()

  gtk.main()
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EXOR or symmetric difference for the Counter class

2010-08-16 Thread Paddy
On 14 Aug, 18:14, Raymond Hettinger pyt...@rcn.com wrote:
 On Aug 12, 1:20 pm, Paddy paddy3...@googlemail.com wrote:

  I find myself needing to calculate the difference between two Counters
  or multisets or bags.

  I want those items that are unique to each bag.

 Tell us about your use cases.  I'm curious how a program would ascribe
 semantic meaning to the result.  The phrase unique to each bag
 doesn't quite cover it, perhaps something like number in either
 source above the minimum held in common.

 AFAICT, I've never needed something like this as a primitive.  Even
 the xor operation for regular sets is rarely used.

  I know how to
  calculate it:

       b = Counter(a=1, b=2)
       c = Counter(a=3, b=1)
       diff = (b - c) + (c - b)
       diff
      Counter({'a': 2, 'b': 1})

 That seems simple enough.
 You could also use:

  diff = (b | c) - (b  c)   # max(b,c) - min(b,c)

 Raymond

Hi Raymond and others,

Lets say you have two *sets* of integers representing two near-copies
of some system, then a measure of their difference could be calculated
as:

len(X.symmetric_difference(Y)) / (len(X) + len(Y)) * 100 %

If the two collections of integers are allowed duplicates then you
need a Counter/bag/multi-set type and the diff calculation I gave
originally.

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


Re: Newbie: strftime object error message

2010-08-16 Thread Mark Lawrence

On 16/08/2010 17:47, fuglyducky wrote:

I am trying to call a function with a couple additional parameters.
Unfortunately, for whatever reason I am unable to get this to work. I
am assuming that line is not passing correctly but I don't understand
why???

I can't share all of the code because it has IP in it but below are
the pertinent snippets.

Thanks in advance!

##

PY: 3.1.2


FUNCTION CALL:
text_file = open(file_name, r)
for line in text_file:
 new_foo = pop_time(current_time, line)
# current_time = datetime.datetime.now()


FUNCTION:
def pop_time(line, cur_time):


Look at the two arguments to pop_time, when you make the actual call 
they are swapped.



 global new_string
 global current_time


 # Generate random time between 0 and 30 seconds
 # Changes the time delta every time function is run
 rand_time = random.randint(0, 30)
 delta_time = datetime.timedelta(seconds=rand_time)

 # Sets the time format for string output
 format_time = cur_time.strftime(%Y-%m-%d %H:%M:%S)


ERROR MSG:
 format_time = cur_time.strftime(%Y-%m-%d %H:%M:%S)
AttributeError: 'str' object has no attribute 'strftime'


NOTE: current_time prints within the function, line does not


HTH.

Mark Lawrence.


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


Re: Newbie: strftime object error message

2010-08-16 Thread MRAB

fuglyducky wrote:

I am trying to call a function with a couple additional parameters.
Unfortunately, for whatever reason I am unable to get this to work. I
am assuming that line is not passing correctly but I don't understand
why???


[snip]
The function's parameters are the wrong way round.
--
http://mail.python.org/mailman/listinfo/python-list


Re: EOFError with fileinput

2010-08-16 Thread Alex van der Spek
Here is an excerpt. It works because the end condition is a fixed number 
(ln==10255), the approximate number of data lines in a file. If I replace 
that condition by EOFError, the program does not do the intended work. It 
appears as if EOFError is always true in this case.


+++

for line in fileinput.input(logs):
   if line.split()[0]=='DataID':
   datsec=True
   ln=0
   if datsec:
   lines[fn].append(line.split())
   ln+=1
   if ln==10255:
   datsec=False
   fileinput.nextfile()
   fn+=1
   print fileinput.filename().rsplit('\\',1)[1]
   fileinput.close()

+++

Regards,
Alex van der Spek


Alex van der Spek zd...@xs4all.nl wrote in message 
news:4c696751$0$22940$e4fe5...@news.xs4all.nl...

Using the fileinput module to process lists of files:


for line in fileinput.input(logs):


Unfortunately, EOFError does not seem to indicate the end-of-file 
condition correctly when using fileinput.


How would you find the EOF file for all the files in the file list 'logs'?

Thank you,
Alex van der Spek 


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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-16 Thread cbr...@cbrownsystems.com
On Aug 16, 1:23 am, Roald de Vries downa...@gmail.com wrote:
 On Aug 15, 2010, at 11:51 PM, Ian Kelly wrote:



  On Sun, Aug 15, 2010 at 4:36 PM, Baba raoul...@gmail.com wrote:
  Hi Mel,

  indeed i thought of generalising the theorem as follows:
  If it is possible to buy n, n+1,…, n+(x-1) sets of McNuggets, for  
  some
  x, then it is possible to buy any number of McNuggets = x, given  
  that
  McNuggets come in x, y and z packs.

  so with diophantine_nuggets(7,10,21) i would need 7 passes
  result:53

  but with (10,20,30) and 10 passes i get no result

  You're on the right track.  In the case of (10,20,30) there is no
  largest exactly purchasable quantity.  Any quantity that does not end
  with a 0 will not be exactly purchasable.

  I suspect that there exists a largest unpurchasable quantity iff at
  least two of the pack quantities are relatively prime, but I have made
  no attempt to prove this.

 That for sure is not correct; packs of 2, 4 and 7 do have a largest  
 unpurchasable quantity.


But 2 is coprime to 7. I think a better counterexample is 6, 10, 15;
no two are coprime, but there is a largest unpurchasable quantity.

 I'm pretty sure that if there's no common divisor for all three (or  
 more) packages (except one), there is a largest unpurchasable  
 quantity. That is: ∀ i1: ¬(i|a) ∨ ¬(i|b) ∨ ¬(i|c), where ¬(x|
 y) means x is no divider of y


It's easy to prove that there is a largest unpurchasble quantity iff
gcd(x,y,z) = 1.

First, suppose d = gcd(x, y, z); then for some x', y', z' we have that
x = d*x', y = d*y', z = d*z'; and so for any a, b, c:

a*x + b*y + c*z = a*d*x' + b*d*y' + c*d*z'
= d*(a*x' + b*y' + c*z')

which means that d must always divide the total number of nuggets
purchasable; thus if d 1, there is no largest unpurchasable quantity
(you cannot purchase n*d + 1 nuggets for any n).

To go the other way, if d = 1, then there exists integers (not
neccessarily positive) such that

a*x + b*y + c*z = 1

so therefore

(a*x)*x + (b*x)*y + (c*x)*z = x

Choose A, B, and C to be positive integers with

A + a*x = 0
B + b*x = 0
C + c*x = 0

Then we get a sequence of x consecutive numbers, all purchasable, via

(A + i*a)*x + (B + i*b)*x + (C + i*c)*z
= (Ax + By + Cz) + i*(ax + by cz)
= (Ax + By + Cz) + i

with i in range(x).

The next consecutive number is then achieved via

(Ax + By + Cz) + x = (A+1)x + By + Cz

and so on.

Cheers - Chas

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


os.stat st_mtime problem

2010-08-16 Thread Alban Nona
Hello,

Im stuck with this problem:
I would like to os.stat st_mtime to copy only the files that have different
modification date.
so I found something on internet using this kind of line:

if os.stat(dest).st_mtime - os.stat(src).st_mtime  1:
shutil.copy2 (src, dst)
So I adapted it to my script like that:

   if sys.argv[1] == 'update':
if os.stat(localPath).st_mtime != os.stat(networkPath).st_mtime:
os.system('xcopy /E /I /Q /Y %s %s' % (networkPath,
localPath))
else:
print Everything match

localPath is equal to : c:\test\prod\
and networkPath to : d:\test\prod\

the content of this paths is another directory: v001, where there some tga
files.

Now I dont even know if os.stat compare the modified version of every files
contained in localPath and networkPath, or does it compare only the v001
info ?
If there a way to do it for every file ?

Thank you !
(PS: I want to avoid filecmp :p)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert bytearray into integer?

2010-08-16 Thread Thomas Jollans
On Monday 16 August 2010, it occurred to Jacky to exclaim:
 Hi there,
 
 Recently I'm facing a problem to convert 4 bytes on an bytearray into
 an 32-bit integer.  So far as I can see, there're 3 ways:

 a) using struct module,

Yes, that's what it's for, and that's what you should be using.

 b) using ctypes module, and

Yeeaah, that would work, but that's really not what it's for. from_buffer 
wants a writable buffer interface, which is unlikely to be what you want.

 c) manually manipulation.

Well, yes, you can do that, but it gets messy when you're working with more 
complex data structures, or you have to consider byte order.

 Are there any other ways?

You could write a C extension module tailored to your specific purpose ;-) 

 number = 1
 1.00135803223e-05
 1.00135803223e-05
 5.96046447754e-06
 -
 
 As the number of benchmarking loops decreasing, method c which is
 manually manipulating overwhelms the former 2 methods.  However, if
 number == 10K, the struct method wins.
 
 Why does it happen?

struct wins because it's built for the job.

As for the small numbers: don't take these numbers seriously. Just don't. This 
may be caused by the way your OS's scheduler handles things for all I know. If 
there is an explanation for this unscientific observation, I have two guesses 
what it might be:
 * struct and ctypes still need to do some setup work, or something
 * somebody is optimising something, but doesn't know what they should be
   optimising in the first place after only a few iterations.

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-16 Thread Ian Kelly
On Mon, Aug 16, 2010 at 12:43 PM, Roald de Vries downa...@gmail.com wrote:
 I'm pretty sure that if there's no common divisor for all three (or more)
 packages (except one), there is a largest unpurchasable quantity. That
 is: ∀
 i1: ¬(i|a) ∨ ¬(i|b) ∨ ¬(i|c), where ¬(x|y) means x is no divider of y

 No.  If you take the (2,4,7) example and add another pack size of 14,
 it does not cause quantities that were previously purchasable to
 become unpurchasable.

 Then what is the common divisor of 2, 4, 7 and 14? Not 2 because ¬(2|7), not
 anything higher than 2 because that's no divisor of 2.

Ah, I misread what you meant as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing variables as object attributes

2010-08-16 Thread Terry Reedy

On 8/16/2010 9:40 AM, Vikas Mahajan wrote:

Hello to all
I am new to python.


Hi, welcome to Python.

Hint 1: 'Variable' is a rather loose term with many meanings. Better to 
think in terms of 'name' ('identifier'), which is specifically defined, 
and 'object'.



I am facing problem to use variables as object attributes.


Your problem is that you have a attribute name stored in a string 
object, rather than being an unquoted literal in the code.



I have to use loop and dynamically add attributes to a
object and for this purpose I have to use variables with object names.


You have to use strings with attribute names. Not uncommon


For example-:
Let us say object car has an attribute engine, then
varname = engine
car.varname = dummy value


setattr(car, varname, dummy value)

is the runtime replacement for

car.engine = dummy value

Note that 'setattr(car, engine, dummy value)' would work but is 
never needed, since if you have the attribute name itself, you just 
write the assignment.


hasattr and getattr are similar.

--
Terry Jan Reedy

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-16 Thread Baba
Hi Chas, Roald,

These are all complicated formula that i believe are not expected at
this level. If you look at the source (see my first submission) you
will see that this exercise is only the second in a series called
Introduction to Programming. Therefore i am convinced that there is
a much simpler solution.

Now, i believe that the number of consecutive passes required to make
this work is equal to the smallest number of pack sizes. So if we have
packs of (9,12,21) the number of passes needed would be 9 and the
theorem would read

If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to
buy any number of nuggets = 9 given that they come in packs of
9,12,21

However i turn in circles because i don't seem to get any results for
some random pack combinations like (9,12,21) or (10,20,30).

The must always be a solution i'm thinking, be it the smallest pack -
1

Thoughts?

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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Elizabeth D Rather

On 8/15/10 10:33 PM, Standish P wrote:
...

I don't understand a lot of your post (and it's clear that I'm not 
alone).  I don't know whether it's a (human) language problem or simply 
an issue of your having read too many books and not having enough 
practical experience, but at least I can try to address the Forth questions.



If Forth is a general processing language based on stack, is it
possible to convert any and all algorithms to stack based ones and
thus avoid memory leaks since a pop automatically releases memory when
free is an intrinsic part of it.


Forth uses two stacks.  The data stack is used for passing parameters 
between subroutines (words) and is completely under the control of the 
programmer.  Words expect parameters on this stack; they remove them, 
and leave only explicit results.  The return stack is used primarily 
for return addresses when words are called, although it is also 
available for auxiliary uses under guidelines which respect the primary 
use for return addresses.


Although implementations vary, in most Forths stacks grow from a fixed 
point (one for each stack) into otherwise-unused memory.  The space 
involved is allocated when the program is launched, and is not managed 
as a heap and allocated or deallocated by any complicated mechanism.  On 
multitasking Forth systems, each task has its own stacks.  Where 
floating point is implemented (Forth's native arithmetic is 
integer-based), there is usually a separate stack for floats, to take 
advantage of hardware FP stacks.



- is forth a general purpose language? Yes
- are all algorithms stack based? No


Does Forth uses stack for all algorithms ? Does it use pointers , ie
indirect addressing ? If it can/must use stack then every algorithm
could be made stack based.


Forth uses its data stack for parameter passing and storage of temporary 
values.  It is also possible to define variables, strings, and arrays in 
memory, in which case their addresses may be passed on the data stack.


Forth is architecturally very simple.  Memory allocations for variables, 
etc., are normally static, although some implementations include 
facilities for heaps as needed by applications.


Hope this helps.  If you are interested in learning more about Forth, 
there are several books available (try Amazon).  Get one of the more 
recent ones, some of which I wrote.


Cheers,
Elizabeth

--
==
Elizabeth D. Rather   (US  Canada)   800-55-FORTH
FORTH Inc. +1 310.999.6784
5959 West Century Blvd. Suite 700
Los Angeles, CA 90045
http://www.forth.com

Forth-based products and Services for real-time
applications since 1973.
==
--
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-16 Thread Standish P
On Aug 16, 12:38 am, Alf P. Steinbach /Usenet alf.p.steinbach
+use...@gmail.com wrote:
 * Standish P, on 16.08.2010 09:20:

  [garble garble]

 Nonsense article We look for an exogenous stack cross-posted to

    [comp.lang.c],
    [comp.lang.c++],
    [comp.theory],
    [comp.lang.python],
    [comp.lang.forth].

 Please refrain from following up on Standish' article.

I am sorry that I did not post one of those porn baiting spams
featuring YOUR MOTHER NUDE that you so like for others to see - AND -
that you never complain about. Go and continue with your work and dont
mess in my threads.

Cheers,
Standish


 Cheers,

 - Alf

 --
 blog at url:http://alfps.wordpress.com

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


Re: Newbie: strftime object error message

2010-08-16 Thread fuglyducky
On Aug 16, 10:27 am, Mark Lawrence breamore...@yahoo.co.uk wrote:
 On 16/08/2010 17:47, fuglyducky wrote:



  I am trying to call a function with a couple additional parameters.
  Unfortunately, for whatever reason I am unable to get this to work. I
  am assuming that line is not passing correctly but I don't understand
  why???

  I can't share all of the code because it has IP in it but below are
  the pertinent snippets.

  Thanks in advance!

  ##

  PY: 3.1.2

  FUNCTION CALL:
  text_file = open(file_name, r)
  for line in text_file:
       new_foo = pop_time(current_time, line)
  # current_time = datetime.datetime.now()

  FUNCTION:
  def pop_time(line, cur_time):

 Look at the two arguments to pop_time, when you make the actual call
 they are swapped.



       global new_string
       global current_time

       # Generate random time between 0 and 30 seconds
       # Changes the time delta every time function is run
       rand_time = random.randint(0, 30)
       delta_time = datetime.timedelta(seconds=rand_time)

       # Sets the time format for string output
       format_time = cur_time.strftime(%Y-%m-%d %H:%M:%S)

  ERROR MSG:
       format_time = cur_time.strftime(%Y-%m-%d %H:%M:%S)
  AttributeError: 'str' object has no attribute 'strftime'

  NOTE: current_time prints within the function, line does not

 HTH.

 Mark Lawrence.

Oh jeez!!! Thanks! Man...looking at this stuff for so long it's easy
to miss the obvious!!! Thanks and sorry for the waste of time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.stat st_mtime problem

2010-08-16 Thread MRAB

Alban Nona wrote:

Hello,
 
Im stuck with this problem:
I would like to os.stat st_mtime to copy only the files that have 
different modification date.

so I found something on internet using this kind of line:
 
if os.stat(dest).st_mtime - os.stat(src).st_mtime  1: 
shutil.copy2 (src, dst) 
So I adapted it to my script like that:
 
   if sys.argv[1] == 'update':

if os.stat(localPath).st_mtime != os.stat(networkPath).st_mtime:
os.system('xcopy /E /I /Q /Y %s %s' % (networkPath, 
localPath))

else:
print Everything match
 
localPath is equal to : c:\test\prod\

and networkPath to : d:\test\prod\
 
the content of this paths is another directory: v001, where there some 
tga files.
 
Now I dont even know if os.stat compare the modified version of every 
files contained in localPath and networkPath, or does it compare only 
the v001 info ?

If there a way to do it for every file ?
 

os.stat doesn't compare anything, it just returns info about a single
file or directory.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Opposite of split

2010-08-16 Thread John Posner

On 8/16/2010 12:44 PM, Alex van der Spek wrote:


Anybody catches any other ways to improve my program (attached), you are
most welcome.


1. You don't need to separate out special characters (TABs, NEWLINEs, 
etc.) in a string. So:


  bt='-999.25'+'\t''-999.25'+'\t''-999.25'+'\t''-999.25'+'\t'+'-999.25'

... can be ...

  bt='-999.25\t-999.25\t-999.25\t-999.25\t-999.25'

BTW, I think you made a couple of lucky errors in this statement. 
Where there are two consecutive apostrophe (') characters, did you mean 
to put a plus sign in between? Your statement is valid because the 
Python interpreter concatenates strings for you:


x = 'foo''bar'
x == 'foobar'
   True

x = 'foo'  'bar'
x == 'foobar'
   True


2. Take a look at the functions in the os.path module:

  http://docs.python.org/library/os.path.html

These functions might simplify your pathname manipulations. (I didn't 
look closely enough to know for sure.)


3. An alternative to:

  alf.write(tp+'\t'+vf+'\t'+vq+'\t'+al+'\t'+bt+'\t'+vs+'\n')

  ... is ...

  alf.write(\t.join((tp, vf, vq, al, bt, vs)) + \n)

4. I suggest using a helper function to bring that super-long 
column-heading line (alf.write('Timestamp ...) under control:


  def multi_field_names(base_name, count, sep_string):
  names = [base_name +   + str(i) for i in range(1, count+1)]
  return sep_string.join(names)

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Problem but tough for me if i want it in linear time

2010-08-16 Thread Frederic Rentsch
On Sun, 2010-08-15 at 15:14 +0200, Peter Otten wrote:
 ChrisChia wrote:
 
  dataList = [a, b, c, ...]
  where a, b, c are objects of a Class X.
  In Class X, it contains self.name and self.number
  
  If i wish to test whether a number (let's say 100) appears in one of
  the object, and return that object,
  is that only fast way of solving this problem without iterating
  through every object to see the number value?
  
  dataList.__contains__ can only check my object instance name...
  anyone can solve this in linear complexity?
 
 Well, iteration as in 
 
 next(item for item in dataList if item.number == 100) 
 
 is O(n) and list.__contains__() has no magic way to do better. If you need 
 O(1) lookup you can use a dict or collections.defaultdict that maps 
 item.number to a list (or set) of X instances:
 
 lookup = {}
 for item in dataList:
 lookup.setdefault(item.number, []).append(item)
 
 print lookup[100]
 
 
 Peter
 

How about 

 [obj for obj in dataList if obj.number == 100]

That should create a list of all objects whose .number is 100. No need
to cycle through a loop. If .number doesn't repeat get your object at
index 0. The approach may seem inefficient for the purpose of extracting
a single item, but the list needs to be gone through in any case and the
list comprehension is surely the most efficient way to do it. 

Frederic


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


  1   2   3   >