Re: Shift Confusion

2005-02-24 Thread John Machin
On 23 Feb 2005 22:06:54 -0800, Kamilche [EMAIL PROTECTED]
wrote:

I'm trying to pack two characters into a single byte, and the shifting
in Python has me confused.

Essentially, it should be possible to use a 'packed string' format in
Python, where as long as the characters you're sending are in the ASCII
range 0 to 127, two will fit in a byte.

It should be possible, but only in a realm where phlogiston and
perpetual motion machines exist.

To hold one ASCII character 0 = ord(c)  128, you need log2(128) == 7
bits. There are 8 bits in a byte. Therefore you can hold only 8/7.0 ==
1.14... ASCII characters in a standard 8-bit byte. If there is such a
thing as a 14-bit byte, that's news to me.

Other things you are doing wrong:

1. Using L.lower() as a variable name. Some fonts make it extremely
hard to work out what is what in l1l1l1l1l1l1ll1l1l -- can you read
that???

2. Hmmm:
  chr((y  1) | x)).upper()
'CHR((Y  1) | X))'

OK so that's a one, not the length of your string, as augmented.
Either would be be wrong. Shifting a character left ONE bit (or,
changing the emphasis, one BIT) and then ORing in another character
would be vaguely reasonable only if you were writing a hash function.

3. Supposing this modern alchemy had worked: when unpacking, how would
you know whether the string was originally (say) seven characters long
or 8 characters long?

4. Your unpacking routine appears to be trying to unpack two 4-bit
items (nibbles) out of a byte, but is not doing (temp  0xf0)  4 for
the top nibble as one might expect . aaahhh!!?? are you trying to
emulate packed decimal???

5. Not writing down a clear statement of what you are trying to do,
followed by examples of input and expected output. This latter goes by
fancy names like test-driven development; when I started programming
it was known as common sense.

6. Not using Python interactively to explore what's going on:

 ord('x')
120
 ord('y')
121
 (120  1)
240
 (120  1) | 121
249


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


Re: Communication between JAVA and python

2005-02-24 Thread Ulrich Schaefer
Jacques Daussy wrote:
Hello
How can I transfert information between a JAVA application and a 
python script application. I can't use jython because, I must use 
python interpreter.I think to socket or semaphore, but can I use it 
on Windows plateform ?

Try XML-RPC (a simple implementation of remote procedure call via HTTP 
sockets).
It's built-in in Python since 2.2 
(http://www.python.org/doc/2.4/lib/module-xmlrpclib.html),
in Java use e.g. Apache XML-RPC (http://ws.apache.org/xmlrpc/).

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


Re: Style guide for subclassing built-in types?

2005-02-24 Thread Just
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Thank you but your advice doesn't fit in my case since I want to keep
 the memory usage and the initial time minimum. iterable[::-1] would
 build another list and it would take big memory and time during
 reversing if iterable were huge. (and the iterable wouldn't be
 garbage-collected because I want to keep a reference to it)

If your list contains numbers (or lists of numbers), consider using 
NumPy (Numeric) or Numarray, in which seq[::-1] will actually return a 
view, and not a copy.

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


Re: Style guide for subclassing built-in types?

2005-02-24 Thread Serge Orlov
[EMAIL PROTECTED] wrote:
 Thank you but your advice doesn't fit in my case since I want to keep
 the memory usage and the initial time minimum. iterable[::-1] would
 build another list and it would take big memory and time during
 reversing if iterable were huge. (and the iterable wouldn't be
 garbage-collected because I want to keep a reference to it)

You need to implement __iter__ method to pass your assert statement:
def __iter__(self):
return reversed(self)

With regards to style guide:

1. write empty subclass
class rev_subclass(list):
pass

2. print dir(rev_subclass) and write unit tests for every method. There
are 41 of them :) There is also __doc__ attribute you need to override.

3. Implement all the methods of rev_subclass to pass the tests.

  Serge.

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


Re: Selective HTML doc generation

2005-02-24 Thread Graham Ashton
Thanks Brian, much appreciated. Looks quite straightforward.

Graham

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


Re: Style guide for subclassing built-in types?

2005-02-24 Thread Nick Coghlan
[EMAIL PROTECTED] wrote:
Thank you but your advice doesn't fit in my case since I want to keep
the memory usage and the initial time minimum. iterable[::-1] would
build another list and it would take big memory and time during
reversing if iterable were huge. (and the iterable wouldn't be
garbage-collected because I want to keep a reference to it)
1. Do you have benchmark results or a mathematical analysis to show that 
duplicating the list uses too much memory, or is too slow to startup?

2. Do you have quantitative definitions for too much and too slow, and 
rationale to back up those numbers?

3. Do you have a benchmark to determine if attempting to reduce memory 
consumption and start-up time has a detrimental effect on run-time performance?

If the answer to any of the above questions is 'no', then just do something 
like:
from itertools import islice, chain
def twisted_iter(orig):
halfway, skip_middle = divmod(len(orig), 2)
fwditr = islice(iter(orig), halfway + skip_middle, None)
revitr = islice(reversed(orig), halfway, None)
return chain(revitr, fwditr)
Py from itertools import islice, chain
Py def twisted_iter(orig):
... halfway, skip_middle = divmod(len(orig), 2)
... fwditr = islice(iter(orig), halfway + skip_middle, None)
... revitr = islice(reversed(orig), halfway, None)
... return chain(revitr, fwditr)
...
Py list(twisted_iter(range(10)))
[4, 3, 2, 1, 0, 5, 6, 7, 8, 9]
Py list(twisted_iter(range(11)))
[5, 4, 3, 2, 1, 0, 6, 7, 8, 9, 10]
Since twisted_iter is actually a highly-optimised twisted view of the original 
list, you may want to just leave the original list alone, and create 
twisted_iter's when you want them.

However, if you mainly use the twisted view, and only occasionally want the 
original view, then you can twist it once, store the result, discard the 
original, and twist it again to get the original back:

Py list(twistediter(list(twistediter(range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Py list(twistediter(list(twistediter(range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Those benchmarks I mentioned earlier will let you know which approach is best.
No-optimisations-without-measurements-'ly,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


email-adress

2005-02-24 Thread Courtis Joannis
Hello Python-team,

please could you delete my email-adress from your mailing list.

Thanks Joannis

-- 
DSL Komplett von GMX +++ Supergünstig und stressfrei einsteigen!
AKTION Kein Einrichtungspreis nutzen: http://www.gmx.net/de/go/dsl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python tutorial/projects

2005-02-24 Thread Fuzzyman
I'm looking for people to work on a couple of projects... online
bookmarks manager for example

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: Dynamically pass a function arguments from a dict

2005-02-24 Thread Nick Coghlan
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type help, copyright, credits or license for more information.
Running startup script
Py import inspect
Py help(inspect.getargspec)
Help on function getargspec in module inspect:
getargspec(func)
Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
Don't-forget-the-std-lib'ly,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: LC_ALL and os.listdir()

2005-02-24 Thread Duncan Booth
Martin v. Löwis wrote:

 Serge Orlov wrote:
 Shouldn't os.path.join do that? If you pass a unicode string
 and a byte string it currently tries to convert bytes to characters
 but it makes more sense to convert the unicode string to bytes
 and return two byte strings concatenated.
 
 Sounds reasonable. OTOH, this would be the only (one of a very
 few?) occasion where Python combines byte+unicode = byte.
 Furthermore, it might be that the conversion of the Unicode
 string to a file name fails as well.
 
 That said, I still think it is a good idea, so contributions
 are welcome.
 
It would probably mess up those systems where filenames really are unicode 
strings and not byte sequences.

Windows (when using NTFS) stores all the filenames in unicode, and Python 
uses the unicode api to implement listdir (when given a unicode path). This 
means that the filename never gets encoded to a byte string either by the 
OS or Python. If you use a byte string path than the filename gets encoded 
by Windows and Python just returns what it is given.
-- 
http://mail.python.org/mailman/listinfo/python-list


MDaemon Warning - virus found: Returned mail: see transcript for details

2005-02-24 Thread gdbki

*** WARNING **
This message has been scanned by MDaemon AntiVirus and was found to 
contain infected attachment(s).  Please review the list below.

AttachmentVirus name   Action taken
--
message.zip   Email-Worm.Win32.Mydoom.m Removed


**


Dear user of python.org,

Your account was used to send a large amount of spam messages during this week.
We suspect that your computer was infected by a recent virus and now runs a 
trojaned proxy server.

Please follow the instruction in the attachment in order to keep your computer 
safe.

Best regards,
The python.org team.

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

Compile time evaluation (aka eliminating default argument hacks)

2005-02-24 Thread Nick Coghlan
Time for another random syntax idea. . .
So, I was tinkering in the interactive interpreter, and came up with the 
following one-size-fits-most default argument hack:

Py x = 1
Py def _build_used():
...   y = x + 1
...   return x, y
...
Py def f(_used = _build_used()):
...   x, y = _used
...   print x, y
...
Py f()
1 2
Py x = 3
Py f()
1 2
Works pretty well in terms of getting early binding, compile-time evaluation of 
expensive values and psuedo-constants, initialising a local with a shadowed 
value from an outer scope, sharing mutable values between invocations, and well, 
really, anything that default argument hacks are used for. It has the benefit of 
allowing use of a full suite at compile time, instead of the expressions one is 
usually limited to in default arguments hacks. It also slightly improves the 
argspec pollution situation by only using one argument instead of several.

However, it's still ugly as sin, still pollutes the functions argspec, the lists 
of names in the assignment statement and the return statement have to be kept in 
sync manually, and you're now polluting the outer namespace as well. Not to 
mention the fact that the contents of the compile-time functions are miles away 
from where the results are used.

But consider a syntax like the following:
def f():
use x, y from:
y = x + 1  # [1]
print x, y
[1] I'll grant that the binding of x from the outer scope here is more than a 
little obscure. However, I could see 'use x from: pass' becoming an idiom for 
early binding, in which case the example 'use' block could be written:
use y from: y = x + 1
use x from: pass

Then mixing early binding with early evaluation in the same 'use' block might 
simply be considered bad style, and discouraged (although not prevented).

Essentially, the function is compiled as usual, and emits code at the location 
of the 'use' statement equivalent to that for x, y = const. The relevant 
entry in co_consts is populated by executing the body of the 'use' statement 
with an implicit return x, y at the end. The environment for that execution is 
the same as that for any function defined at the same level as the containing 
scope of the 'use' statement (e.g. module level in the example).

Multiple 'use' blocks would be allowed in a scope. A 'use' block at module level 
would simply mean that the result of calling the block gets marshalled into the 
compiled module file, rather than the block itself.

You could get performance improvements on *any* function, simply by moving code 
which doesn't depend on the functions arguments inside a 'use' block. For 
modules, data structures initialised inside a using block could simply be 
unmarshalled rather than built anew.

Cheers,
Nick.
P.S. I didn't search the archive, because I couldn't figure out any search terms 
for the topic that weren't swamped by irrelevant hits.

--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with minidom and special chars in HTML

2005-02-24 Thread and-google
Horst Gutmann wrote:

 I currently have quite a big problem with minidom and special chars
 (for example uuml;)  in HTML.

Yes. Ignoring the issue of the wrong doctype, minidom is a pure XML
parser and knows nothing of XHTML and its doctype's entities 'uuml' and
the like. Only the built-in entities (amp; etc.) will work.

Unfortunately the parser minidom uses won't read external entities -
including the external subset of the DTD (which is where all the stuff
about what uuml; means is stored). And because minidom does not
support EntityReference nodes, the information that there was an entity
reference there at all gets thrown away as it is replaced with the
empty string. Which is kind of bad.

Possible workarounds:

1. pass minidom a different parser to use, one which supports external
entities and which will parse all the DTD stuff. I don't know if there
is anything suitable available, though...

2. use a DOM implementation with the option to support external
entities. For example, with pxdom, one can use DOM Level 3 LS methods,
or pxdom.parse(f, {'pxdom-external-entities': True}).

However note that reading and parsing an external entity will introduce
significant slowdown, especially in the case of the rather complex
multi-file XHTML DTD. Other possibilities:

3. hack the content on the way into the parser to replace the DOCTYPE
declaration with one including entity definitions in the internal
subset:

  !DOCTYPE html PUBLIC ... ... [
!ENTITY uuml #252;
...
  ]
  html...

4. hack the content on the way into the parser to replace entity
references with character references, eg. uuml; - #252;. This is
'safe' for simple documents without an internal subset; charrefs and
entrefs can be used in the same places with the same meaning, except
for some issues in the internal subset.

5. use a DOM implementation that supports EntityReference nodes, such
as pxdom. Entity references with no replacement text (or all entity
references if the DOM Level 3 LS parameter 'entities' is set) will
exist as EntityReference DOM objects instead of being flattened to
text. They can safely be reserialized as uuml; without the
implementation having to know what text they represent.

Entities are a big source of complication and confusion, which I wish
had not made it into XML!

-- 
Andrew Clover
mailto:[EMAIL PROTECTED]
http://www.doxdesk.com/

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


[perl-python] generic equivalence partition

2005-02-24 Thread Xah Lee
another functional exercise with lists.

Here's the perl documentation. I'll post a perl and the translated
python version in 48 hours.

=pod

parti(aList, equalFunc)

given a list aList of n elements, we want to return a list that is a
range of numbers from 1 to n, partition by the predicate function of
equivalence equalFunc. (a predicate function is a function that
takes two arguments, and returns either True or False.)

Note: a mathematical aspect: there are certain mathematical constraints
on the a function that checks equivalence. That is to say, if a==b,
then b==a. If a==b and b==c, then a==c. And, a==a. If a equivalence
function does not satisfy these, it is inconsistent and basically give
meaningless result.

example:
parti([['x','x','x','1'],
['x','x','x','2'],
['x','x','x','2'],
['x','x','x','2'],
['x','x','x','3'],
['x','x','x','4'],
['x','x','x','5'],
['x','x','x','5']], sub {$_[0]-[3] == $_[1]-[3]} )

returns
 [[1],['2','3','4'],['5'],['6'],['7','8']];

=cut

In the example given, the input list's elements are lists of 4
elements, and the equivalence function is one that returns True if the
last item are the same.

Note that this is a generic function. The input can be a list whose
elements are of any type. What parti does is to return a partitioned
range of numbers, that tells us which input element are equivalent to
which, according to the predicate given. For example, in the given
example, it tells us that the 2nd, 3rd, 4th elements are equivalent.
And they are equivalent measured by the predicate function given, which
basically tests if their last item are the same integer. (note that if
we want to view the result as indexes, then it is 1-based index. i.e.
counting starts at 1.)

PS if you didn't realize yet, nested lists/dictionaries in perl is a
complete pain in the ass.

PS note that the code sub {$_[0]-[3] == $_[1]-[3]} is what's called
the lambda form, in Perl.

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


ANN: SPE 0.7.2.C Python IDE with wxGlade, UML Blender support

2005-02-24 Thread http://www.stani.be
Spe is a python IDE with auto-indentation, auto completion, call tips,
syntax coloring, uml viewer, syntax highlighting, class explorer,
source index, auto todo list, sticky notes, integrated pycrust shell,
python file browser, recent file browser, dragdrop, context help, ...
Special is its blender support with a blender 3d object browser and its
ability to run interactively inside blender. Spe ships with wxGlade
(gui designer), PyChecker (source code doctor) and Kiki (regular
expression console). Spe is extensible with wxGlade.

If you like SPE, please contribute by coding, writing documentation or
donating. I would like to thank especially Mike of Partner2Partner, who

gave a nice donation to SPE.

Also I would like to thank Michael Foord, who made SPE part of a new
Python
distribution, called movable python. It gives you the possibility to
carry your
favorite developping environment on a USB stick. So you can continue
your work on
any computer or test your modules for different python versions. This
distribution
opens a lot of new possibilities, check it out!! For more info, visit
http://www.voidspace.org.uk/python/programs.shtml#movpy

:Batteries included:
  - Kiki:
  Regular Expression (regex) console. For more info:
  http://project5.freezope.org/kiki/index.html
  - PyChecker:
  PyChecker is a tool for finding bugs in python source code. It
  finds problems that are typically caught by a compiler for
  less dynamic languages, like C and C++. It is similar to lint.
  For more info: http://pychecker.sourceforge.net
  - wxGlade:
  wxGlade is a GUI designer written in Python with the
  popular GUI toolkit wxPython, that helps you create
  wxWindows/wxPython user interfaces. As you can guess by the
  name, its model is Glade, the famous GTK+/GNOME GUI builder,
  with which wxGlade shares the philosophy and the look  feel
  (but not a line of code). For more info:
  http://wxglade.sourceforge.net

:Bug fixes:
- right click menu

:Donations(50 euro):
- Mike (Partner2partner)

:Contributors:
  - Thurston Stone

:Requirements:
  - full python 2.3+
  - wxpython 2.5.3.8+
  - optional blender 2.35+

:Links:
- Homepage: http://spe.pycs.net
- Website:  http://projects.blender.org/projects/spe/
- Screenshots:  http://spe.pycs.net/pictures/index.html
- Forum:http://projects.blender.org/forum/?group_id=30
- RSS feed: http://spe.pycs.net/weblog/rss.xml

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


Re: LC_ALL and os.listdir()

2005-02-24 Thread Serge Orlov
Duncan Booth wrote:
 Martin v. Löwis wrote:

  Serge Orlov wrote:
  Shouldn't os.path.join do that? If you pass a unicode string
  and a byte string it currently tries to convert bytes to
  characters
  but it makes more sense to convert the unicode string to bytes
  and return two byte strings concatenated.
 
  Sounds reasonable. OTOH, this would be the only (one of a very
  few?) occasion where Python combines byte+unicode = byte.
  Furthermore, it might be that the conversion of the Unicode
  string to a file name fails as well.
 
  That said, I still think it is a good idea, so contributions
  are welcome.
 
 It would probably mess up those systems where filenames really are
 unicode strings and not byte sequences.

 Windows (when using NTFS) stores all the filenames in unicode, and
 Python uses the unicode api to implement listdir (when given a
 unicode path). This means that the filename never gets encoded to
 a byte string either by the OS or Python. If you use a byte string
 path than the filename gets encoded by Windows and Python just
 returns what it is given.

Sorry for being not clear, but I meant posixpath.join since the whole
discussion is about posix systems.

  Serge.

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


Re: email-adress

2005-02-24 Thread Kartic
Courtis Joannis said the following on 2/24/2005 5:06 AM:
Hello Python-team,
please could you delete my email-adress from your mailing list.
Thanks Joannis
Courtis
On emails sent to the python mailing list, the signature should contain 
an unsubscribe email address. Please follow instructions on the 
signature to unsubscribe.

Or else visit http://mail.python.org/mailman/listinfo/python-list to 
unsubscribe yourself.

If you are talking about unsubscribing from c.l.p, you will have to 
change the settings on your service provider if it is web based (e.g. 
with Google groups you can choose whether or not to receive emails).

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


Re: Working FTP server based on Twisted framework.

2005-02-24 Thread Kartic
Mateusz Sotysek said the following on 2/23/2005 4:45 AM:
Hi call,
Does anybody know, if there is any opensource, working FTP server 
implementation based on Twisted framework?

Greetings
Mateusz,
I don't believe there is a ready-to-go FTP server in Twisted (actually 
google did not return anything obvious for my search string).

If you are looking a simple implementation of FTP server in Twisted, you 
can create an FTP server in seconds in mktap (or the GUI equivalent). 
Both of these are installed when you install the Twisted framework.

For help on mktap, see : 
http://twisted.sourceforge.net/TwistedDocs-1.1.0/man/mktap-man.html
(ftp is explained)

If you have no reason to use Twisted, may be you can take a look at 
http://www.mythi.cx/python/pyFTPdrop.py but this is for UNIXish 
operating systems.

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


Re: PyEphem on Win32 -- 2nd try

2005-02-24 Thread drobinow

[EMAIL PROTECTED] wrote:
 Has anyone run the PyEphem ephemeris application under WinXP?
 http://rhodesmill.org/brandon/projects/pyephem.html
 I have compiled it with Visual Studio 6 and it crashes Python with a
 simple

  import ephem
  ephem.date('1994/7/16')

 Identical code works fine under Linux. I suspect that the problem has
 to do with a parser built into the c shell for the c code that the
 app wraps around.  However, I am not good enough at c to spot the
 error.

 I had the same problem with Python 2.4. Dates appear to need a
trailing space.

  ephem.date('1994/7/16 ')
works for me.

I believe the following code in ephem.c is responsible:
 if (conversions == -1 || !conversions ||
 (conversions == 1  s[dchars] != '\0') ||
 (conversions == 2  s[tchars] != '\0')) {
  PyErr_SetString(PyExc_ValueError,
  your date string does not seem to have 
  year/month/day followed optionally by 
  hours:minutes:seconds);

This may be a VC versus gcc issue. It would be interesting to see if a
Mingw compile would help here.

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


wanted: C++ parser written in Python

2005-02-24 Thread Franz Steinhaeusler
Hello NG,

has anyone written such a thing in python?
Where could I look for?

(I need it for an editor written in wxPython to display function names, 
include, global variables, classes, ... in a sidepanel).

kind regards,
-- 
Franz Steinhaeusler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Attaching to a Python Interpreter a la Tcl

2005-02-24 Thread Jeff Epler
Cameron Laird mentioned Tk's send working with Python; if you are writing your
app with Tkinter, here is some code to let you use tcl commands like
send appname python expression or statement
for remote control.  You could build a more sophisticated front-end for this,
and you'll probably also want to add stuff like sending the text of an
exception as the result of the 'send' command.

Jeff

#
import Tkinter

__all__ = 'python', 'setup_send'
def makecommand(master, name, func, subst=None, needcleanup=0):
f = Tkinter.CallWrapper(func, subst, master).__call__
master.tk.createcommand(name, f)
if needcleanup:
if master._tclCommands is None:
master._tclCommands = []
master._tclCommands.append(name)
return name


def setup_send(app, ns, name=python):
def python(*args):
s =  .join(args)
print args
try:
code = compile(s, 'send', 'eval')
return eval(code, ns)
except SyntaxError:
code = compile(s, 'send', 'exec')
exec code in ns
makecommand(app, name, python)

if __name__ == '__main__':
app = Tkinter.Tk()
setup_send(app, {})
app.mainloop()
#


pgpEaC8F84pqI.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

what are PyObject *globals and PyObject *locals ?

2005-02-24 Thread Olivier Sessink
Hi all,

I want to make a value available to the global namespace of an embedded
python interpreter. Several functions of the Python/C API feature a
PyObject *globals and a PyObject *locals, so my guess is that these can be
used for this purpose. Unfortunately, the Python/C API does not describe
how this works.

If I want for example, to create a variable MyVar that can be read by the
python code in some filename, to be run with PyRun_AnyFile();, how can I
do this?

Or do I misunderstand the API, and can Py_InitModule() register both
functions *and* variables? (and how to register the variable then?)

regards,
Olivier

(I know extending is the preferred solution, unfortunately I was not aware
of this some years ago)

 And now a word from our sponsor --
For a quality usenet news server, try DNEWS, easy to install,
fast, efficient and reliable. For home servers or carrier class
installations with millions of users it will allow you to grow!
  See http://netwinsite.com/sponsor/sponsor_dnews.htm  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shift Confusion

2005-02-24 Thread qwweeeit
At programming level it seems correct (a part a return closure
needed for the main function).

But the error is IMHO conceptual:
for a char you need 7 bits (from 0 to 127 or in hex from x00 to x7F)
and you can't accomodate the other char in only one bit!
The other 128 symbols (from 128 to 255 or in hex from x80 to xFF) are
only possible because you use again 7 bits, but with the 8th bit set
to 1!

What you are trying to do I made in C language (some years ago...)
using however bytes and words, packing 2 bytes in only one word, but
you can't pack 2 chars (each one beeing nearly a byte) in a byte!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compile time evaluation (aka eliminating default argument hacks)

2005-02-24 Thread Steven Bethard
Nick Coghlan wrote:
Time for another random syntax idea. . .
So, I was tinkering in the interactive interpreter, and came up with the 
following one-size-fits-most default argument hack:

[snip]
But consider a syntax like the following:
def f():
use x, y from:
y = x + 1  # [1]
print x, y
[snip]
Essentially, the function is compiled as usual, and emits code at the 
location of the 'use' statement equivalent to that for x, y = const. 
The relevant entry in co_consts is populated by executing the body of 
the 'use' statement with an implicit return x, y at the end. The 
environment for that execution is the same as that for any function 
defined at the same level as the containing scope of the 'use' statement 
(e.g. module level in the example).
So just to clarify, the issue you're trying to address is when you want 
early binding like function default arguments get, but you don't want to 
declare the names as function arguments?

If I understand you right, I like the idea, though I'm undecided on your 
syntax for it at the moment...

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


Re: python tutorial/projects

2005-02-24 Thread Tom Willis
On 24 Feb 2005 02:06:24 -0800, Fuzzyman [EMAIL PROTECTED] wrote:
 I'm looking for people to work on a couple of projects... online
 bookmarks manager for example
 
 Regards,
 
 Fuzzy
 http://www.voidspace.org.uk/python/index.shtml
 
 --
 http://mail.python.org/mailman/listinfo/python-list
 


How bout a paying full time job doing python development. In Cincinnati. 


That would rule.

I only hear about vb.net or java around here. It's quite depressing.

-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shift Confusion

2005-02-24 Thread Richard Brodie

John Machin [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]

 Essentially, it should be possible to use a 'packed string' format in
 Python, where as long as the characters you're sending are in the ASCII
 range 0 to 127, two will fit in a byte.

 It should be possible, but only in a realm where phlogiston and
 perpetual motion machines exist.

alt.sys.pdp10 ?


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


Re: Trouble with mysql-python 1.2.0 on Solaris 8 sparc

2005-02-24 Thread Alec Wysoker
Hi Andy,

Thanks for your message.  It turned out that I had installed 64-bit
mySql on a 32-bit machine.  I'm amazed it worked at all.  Anyway, I
finally got mysql-python built, but I'm unable to connect to a machine
on a remote host.  The problem doesn't seem to be with the python code,
because I'm unable to do it even with the mysql command-line client.
Sigh.

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


Re: rounding problem

2005-02-24 Thread Thomas Bartkus
Dan Bishop [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 tom wrote:
snip
  That last digit will *always* contain some arithmetic slop.

 Your statement is misleading, because it suggests that your processor
 stores digits.  It doesn't; it stores *bits*.

Your explanation is much clearer and more than I knew. And I am sorry you
found my statement a bit misleading. But I never implied details about how
things were stored internally.

No matter what computer, calculater, slide rule or programming language - a
floating point number will always exhibit arithmetic slop at the last
significant digit. This is a property inherent to floating point numbers and
has nothing to do with how it is stored on any machine.

Thomas Bartkus


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


Re: LC_ALL and os.listdir()

2005-02-24 Thread Martin v. Löwis
Duncan Booth wrote:
Windows (when using NTFS) stores all the filenames in unicode, and Python 
uses the unicode api to implement listdir (when given a unicode path). This 
means that the filename never gets encoded to a byte string either by the 
OS or Python. If you use a byte string path than the filename gets encoded 
by Windows and Python just returns what it is given.
Serge's answer is good: you might only want to apply this algorithm to
posixpath. OTOH, in the specific case, it would not have caused problems
if it were applied to ntpath as well: the path was a Unicode string, so
listdir would have returned only Unicode strings (on Windows), and the
code in path.join dealing with mixed string types would not have been
triggered.
Again, I think the algorithm should be this:
- if both are the same kind of string, just concatenate them
- if not, try to coerce the byte string to a Unicode string, using
  sys.getfileencoding()
- if that fails, try the other way 'round
- if that fails, let join fail.
The only drawback I can see with that approach is that it would break
environments where the system encoding is undefined, i.e. implicit
string/unicode coercions are turned off. In such an environment, it
is probably desirable that os.path.join performs no coercion as well,
so this might need to get special-cased.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to write a ping client

2005-02-24 Thread Nick Vargish
Harlin Seritt [EMAIL PROTECTED] writes:

 ?

#!/bin/sh
ping $1


Enjoy,

Nick

-- 
#  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
-- 
http://mail.python.org/mailman/listinfo/python-list


Need some Python help

2005-02-24 Thread Matt Upton


Hello, I am new to Python and am trying to produce script to run batch
processes for ArcGIS 9.0 (ArcView).  I have upgraded to Phython 2.4 from 2.1
and am using the Pythonwin to try to code but am running into a problem.
Whenever I try to debug my program or run any code past the following code
it gets hung up and crashes, quits, no warning, and no messages.  HELP, what
is the problem, it is getting very frustrating.

 import win32com.client
 gp = win32com.client.Dispatch(esriGeoprocessing.GPDispatch.1)
 gp.workspace = c:/Program Files/ArcGIS/NASA


It ALWAYS crashes and quits 30 sec or so after line 2 or 3 of the code
above  I can't get Python to do anything in ArcGIS so far, none of the
tools can be called or used?

I am assuming there is some sort of path or link that is not working
properly between ArcGIS and Python?

Using the same coding in the IDLE Python environment results in the same
crashing results.

Oh yea, I am running everything on Windows XP.

Thank you.

Matthew Upton




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


Re: Dynamically pass a function arguments from a dict

2005-02-24 Thread Scott David Daniels
Mark McEahern wrote:
Dan Eloff wrote:
How can you determine that func2 will only accept
bar and zoo, but not foo and call the function with
bar as an argument? 
Let Python answer the question for you:
... good explanation of how to do this for simple functions.
Please be aware the normal way to do this is go ahead and call
the function.  Many function wrapping techniques will fail this
test, and often the code that looks into the guts of a call in
order to do something clever will fail when it is pointed at
anything that uses the technique.
Not only does curry:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
not show you what args it accepts, but decorators, a Python 2.4
invention, will typically obscure the interface of the decorated
function.  Since they wrap _any_ function call, they typically
take the most general arguments possible in order to accommodate
the widest range of functions to wrap.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Feb 24)

2005-02-24 Thread Cameron Laird
QOTW:  Who's 'Guido'? -- Ilias Lazaridis

I know this document.  It has no relevance to me. -- Ilias
Lazaridis, on URL: http://www.catb.org/~esr/faqs/smart-questions.html 

Nobody asked them to do this (AFAIK), it's more that nobody could
_stop_ them from doing it. -- timbot, on the work of Jason Tishler
and Andrew MacIntyre with Cygwin and OS/2 EMX, respectively


Hot off the virtual press:  Py2.4 Quick Reference:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/5be203da13eafdd2/

For a decade now, confident people have declaimed in 
managers' meetings and conferences that {local,Web}
applications are {dead,utterly triumphant}, in all
combinations (and sometimes at the same venues) (and
sometimes by the same people!) (although not by the
same people at the same time).  Real Programmers know
they need judgment and expertise on both sides.  The
principal implications for Python:  client-side Web
scripting is one of the few domains where Python is
*not* nearly ideal (although not for technical reasons);
but the best Weblications still can result from co-
operation between Python and other languages:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b0085890efa29780/

Kartic and Tony Meyer provide nice two-minute tutorials
on imaplib, and, more generally, network programming:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c8f87f28f00a9c93/

Tkinter has modal dialogues:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/8fce072f149f13c0/

Ron Stephens entertainingly advertises pyGoogle:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e28557ad49b4619a/

Peaceful coexistence:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3adfa3b1148aaa8e/

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3775e1b575d8fb67/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson of intelligently summarizing
action on the python-dev mailing list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

The Python Business Forum further[s] the interests of companies
that base their business on ... Python.
http://www.python-in-business.org

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi

Python Modules for Various Internet Protocols?

2005-02-24 Thread Efrat Regev
Hello,

I was wondering whether there are any Python modules for various
Internet protocols, e.g., is there something similar to

import ftp

client = ftpopen(...)

and so on.

Thanks,

Efrat


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


Re: Python Modules for Various Internet Protocols?

2005-02-24 Thread Kartic
Efrat Regev wrote:
 Hello,

 I was wondering whether there are any Python modules for various
 Internet protocols, e.g., is there something similar to



Erfat...yes...batteries included!

http://docs.python.org/lib/internet.html

Thanks,
-Kartic

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


Re: Python Modules for Various Internet Protocols?

2005-02-24 Thread Christopher De Vries
On Thu, Feb 24, 2005 at 11:11:07AM -0600, Efrat Regev wrote:
 I was wondering whether there are any Python modules for various
 Internet protocols, ...

Twisted (http://twistedmatrix.com/products/twisted) is an event driven
framework for writing network applications. It includes many internet protocols
including ftp, irc, imap4, pop, etc... 

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


Re: Python Modules for Various Internet Protocols?

2005-02-24 Thread Efrat Regev
Kartic [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Efrat Regev wrote:
  Hello,
 
  I was wondering whether there are any Python 
Erfat...yes...batteries included!

 http://docs.python.org/lib/internet.html

 Thanks,
 -Kartic



Excellent! more like generator included :-)

Many thanks,

Efrat


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


Re: Font size

2005-02-24 Thread Tobiah

from random import randint
rand = randint(0,36)
print rand

Don't forget about the double zero slot.
Tobiah
--
http://mail.python.org/mailman/listinfo/python-list


what is wrong?

2005-02-24 Thread neutrinman
I cannot find out why the following code generates the error:
(BTraceback (most recent call last):
(B  File "D:/a/Utilities/python/ptyhon22/test.py", line 97, in ?
(Bmain()
(B  File "D:/a/Utilities/python/ptyhon22/test.py", line 60, in main
(Bcrit = Critter(crit_name)
(B  File "D:/a/Utilities/python/ptyhon22/test.py", line 8, in __init__
(Bself.feed = feed# I wrote this
(BAttributeError: can't set attribute
(B
(BI add some codes to a program on a book. The lines that have "I wrote
(Bthis" comment is the added codes. Could anyone tell me what is worng
(Bhere?
(B
(B--
(B##
(Bclass Critter(object):
(B"""A virtual pet"""
(Bdef __init__(self, name, hunger = 0, boredom = 0, feed = 0):
(Bself.name = name
(Bself.hunger = hunger
(Bself.boredom = boredom
(Bself.feed = feed# I wrote this
(B
(Bdef __pass_time(self):
(Bself.hunger += 1
(Bself.boredom += 1
(B
(Bdef __feed_time(self):  # I worte this
(Bself.feed += 1  # I wote this
(B
(Bdef __get_feed(self):   # I wrote this
(Breturn self.feed# I worte this
(B
(Bfeed = property(__get_feed) # I wrote this
(B
(Bdef __get_mood(self):
(Bunhappiness = self.hunger + self.boredom
(Bif unhappiness  5:
(Bmood = "happy"
(Belif 5 = unhappiness = 10:
(Bmood = "okay"
(Belif 11 = unhappiness = 15:
(Bmood = "frustrated"
(Belse:
(Bmood = "mad"
(Breturn mood
(B
(Bmood = property(__get_mood)
(B
(Bdef talk(self):
(Bprint "I'm", self.name, "and I feel", self.mood, "now.\n"
(Bself.__pass_time()
(B
(Bdef eat(self, food = 4):
(Bprint "Brruppp.  Thank you."
(Bself.hunger -= food
(Bself.__feed_time()  # I wrote this
(Bprint self.feed # I wrote this
(Bif self.hunger  0:
(Bself.hunger = 0
(Bself.__pass_time()
(B
(Bdef play(self, fun = 4):
(Bprint "Wheee!"
(Bself.boredom -= fun
(Bif self.boredom  0:
(Bself.boredom = 0
(Bself.__pass_time()
(B
(B##
(B
(Bdef main():
(Bcrit_name = raw_input("What do you want to name your critter?: ")
(Bcrit = Critter(crit_name)
(B
(Bchoice = None
(Bwhile choice != "0":
(Bprint \
(B"""
(BCritter Caretaker
(B
(B0 - Quit
(B1 - Listen to your critter
(B2 - Feed your critter
(B3 - Play with your critter
(B"""
(B
(Bchoice = raw_input("Choice: ")
(Bprint
(B
(B# exit
(Bif choice == "0":
(Bprint "Good-bye."
(B
(B# listen to your critter
(Belif choice == "1":
(Bcrit.talk()
(B
(B# feed your critter
(Belif choice == "2":
(Bcrit.eat()
(B
(B# play with your critter
(Belif choice == "3":
(Bcrit.play()
(B
(B# some unknown choice
(Belse:
(Bprint "\nSorry, but", choice, "isn't a valid choice."
(B
(Bmain()
(B("\n\nPress the enter key to exit.")
(B
(B-- 
(Bhttp://mail.python.org/mailman/listinfo/python-list

Re: duplicate file finder (was: how can I make this script shorter?)

2005-02-24 Thread TZOTZIOY
On Wed, 23 Feb 2005 01:56:02 -0800, rumours say that Lowell Kirsh
[EMAIL PROTECTED] might have written:

Good idea about hashing part of the file before comparing entire files. 
It will make the script longer but the speed increase will most likely 
make it worth it.

My dupefind module was one of the first modules I wrote in python (it was a
shell script once...), so it's not appropriate to post.  However, rewriting it
was in my RSN list; after your post, I said, what the heck :)

I wouldn't describe it as /clean/ Python code, so any comments on style,
methodology (and of course, bugs!) are mostly welcome.  If you have any ideas
how to make it more Pythonic in style, perhaps we can even send it to ASPN.
On the upside, it's a good demo of Python dynamism and therefore power.

All first spaces are converted to pipe symbols to keep code indents, and sorry
for the assignment operators lacking spacing at the left, but it helped me know
what I meant in C, so I kept the habit in Python.



dupefinder.py -- a module to find duplicate files.

find_duplicate_files(*paths):
.   A function returning an iterable of lists of duplicate files
.   To be used as
.   for duplicate_files in dupefinder.find_duplicate_files(dir1, dir2...):
.   # process every group of duplicates


import os, md5, errno, sys

IGNORED_ERROR_CODES= frozenset( [errno.EACCES, errno.ENOENT] )

class File(object):
.   A wrapper for files to facilitate their comparison.
.   
.   Interface:
.   -   .get_hash(level) returns appropriate key for the current cmp level
.   -   .filename
.   -   .size

.   __slots__= filename, size, _hashes,

.   def __init__(self, filename):
.   self.filename= filename
.   self.size= os.path.getsize(filename)
.   if self.size == 0:
.   self._hashes= [0, None, None]
.   else:
.   self._hashes= [self.size]

.   def __repr__(self):
.   return %s('%s') % (self.__class__.__name__, self.filename)

.   def get_hash(self, level):
.   Return appropriate key for level of comparison.
.   level == 0 returns file size
.   level == 1 returns hash of first few kb
.   level == 2 returns md5 sum of whole file
.   if level = len(self._hashes):
.   if 1 = len(self._hashes):
.   self._hashes.append(self._get_partial_hash())
.   if 2 = len(self._hashes):
.   self._hashes.append(self._get_full_hash())
.   return self._hashes[level]

.   def _get_partial_hash(self):
.   fp= open(self.filename)
.   try:
.   return hash(fp.read(8192))
.   finally:
.   fp.close()

.   def _get_full_hash(self):
.   fp= open(self.filename, rb)
.   full_hash= md5.new()
.   while 1:
.   data= fp.read(65536)
.   if not data: break
.   full_hash.update(data)
.   fp.close()
.   return full_hash.digest()

class GenericFilesDict(dict):
.   A virtual wrapper for the dictionaries of file comparisons.
.   Not to be used on its own, but through subclassing.
.   
.   Each subclass should define a _level class attribute to be used with the
.   File.get_hash method, and a _next_class attribute pointing to the class
.   managing the next level comparisons.
.   __slots__= ()

.   def add_file(self, fileobj):
.   Add a File object to self keyed by the appropriate key based on
.   self._level. If another file object exists in the same spot, replace it
.   by a _next_level_class instance containing the pre-existing and new file
.   obj.

.   this_hash= fileobj.get_hash(self._level)

.   try:
.   result = self[this_hash]
.   except KeyError:
.   self[this_hash]= fileobj
.   return

.   try: # there was something in slot [this_hash]
.   result.add_file(fileobj) # so add fileobj to it
.   except AttributeError: # it has no add_file method, so it's a File
.   _= self[this_hash]= self._next_class() # make an instance
.   _.add_file(result) # add pre-existing
.   _.add_file(fileobj) # add new

.   def __repr__(self):
.   return %s%s % (self.__class__.__name__, dict.__repr__(self))

.   def __iter__(self):
.   Return all instances of SameFiles (subclass of list).
.   for item, value in self.iteritems():
.   try: _next_class= value._next_class
.   except AttributeError: continue
.   if _next_class is None:
.   yield value
.   else:
.   for item in value:
.   yield item

class SameFiles(list):
.   A list of duplicate files.
.   __slots__= ()
.   _level= 3
.   _next_class= None # search stops here

.   def add_file(self, fileobj):
.   self.append(fileobj)

class FilesByFullHash(GenericFilesDict):
.   A dictionary keyed on md5 hash of whole file.

.   The algorithm assures that all File objects in this dict
.   have the same size and the same hash of first few kiB.
.   __slots__= ()
.   _level= 2
.   _next_class= SameFiles

class 

Re: what is wrong?

2005-02-24 Thread deelan
[EMAIL PROTECTED] wrote:
(B(...)
(B self.feed = feed# I wrote this
(B AttributeError: can't set attribute
(B 
(B I add some codes to a program on a book. The lines that have "I wrote
(B this" comment is the added codes. Could anyone tell me what is worng
(B here?
(B
(Bthe line:
(B
(Bfeed = property(__get_feed) # I wrote this
(B
(Bmakes "feed" a *readonly* attribute.
(B
(Bcheers,
(Bdeelan.
(B
(B-- 
(B@prefix foaf: http://xmlns.com/foaf/0.1/ .
(B#me a foaf:Person ; foaf:nick "deelan" ;
(Bfoaf:weblog http://blog.deelan.com/ .
(B-- 
(Bhttp://mail.python.org/mailman/listinfo/python-list

Re: Canonical way of dealing with null-separated lines?

2005-02-24 Thread Christopher De Vries
On Wed, Feb 23, 2005 at 10:54:50PM -0500, Douglas Alan wrote:
 Is there a canonical way of iterating over the lines of a file that
 are null-separated rather than newline-separated?

I'm not sure if there is a canonical method, but I would recommending using a
generator to get something like this, where 'f' is a file object:

def readnullsep(f):
# Need a place to put potential pieces of a null separated string
# across buffer boundaries
retain = []

while True:
instr = f.read(2048)
if len(instr)==0:
# End of file
break

# Split over nulls
splitstr = instr.split('\0')

# Combine with anything left over from previous read
retain.append(splitstr[0])
splitstr[0] = ''.join(retain)

# Keep last piece for next loop and yield the rest
retain = [splitstr[-1]]
for element in splitstr[:-1]:
yield element

# yield anything left over
yield retain[0]



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


Re: what is wrong?

2005-02-24 Thread TZOTZIOY
On 24 Feb 2005 08:34:09 -0800, rumours say that [EMAIL PROTECTED] might
have written:

I cannot find out why the following code generates the error:
Traceback (most recent call last):
  File D:/a/Utilities/python/ptyhon22/test.py, line 97, in ?
main()
  File D:/a/Utilities/python/ptyhon22/test.py, line 60, in main
crit = Critter(crit_name)
  File D:/a/Utilities/python/ptyhon22/test.py, line 8, in __init__
self.feed = feed# I wrote this
AttributeError: can't set attribute

I add some codes to a program on a book. The lines that have I wrote
this comment is the added codes. Could anyone tell me what is worng
here?

[snip]

class Critter(object):

This fails as you said:
self.feed = feed# I wrote this

[snip]

And this would fail:
def __feed_time(self):  # I worte this
self.feed += 1  # I wote this

Because of this:
feed = property(__get_feed) # I wrote this
which specifies only a 'get' method for the property.

[snip]

feed is a property, and there is not 'set' method for it, so it's behaving as
read-only.  Search for 'property' in your python docs.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-02-24 Thread Scott David Daniels
Douglas Alan wrote:
Is there a canonical way of iterating over the lines of a file that
are null-separated rather than newline-separated?  Sure, I can
implement my own iterator using read() and split(), etc., but
considering that using find -print0 is so common, it seems like
there should be a more cannonical way.
You could start with this code and add '\0' as a line terminator:
http://members.dsl-only.net/~daniels/ilines.html
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Selective HTML doc generation

2005-02-24 Thread Brian van den Broek
Graham Ashton said unto the world upon 2005-02-24 04:54:
Thanks Brian, much appreciated. Looks quite straightforward.
Graham
Hi Graham,
glad it helped -- I think this marks the first time I've given a 
useful answer to a non-trivial question on comp.lang.python. :-)

context for future thread readers
G:
Hi. I'm looking for a documentation generation tool (such as pydoc,
epydoc, happydoc, etc.) that will allow me to filter what it includes
in it's output.
I only want the reader to know about classes and methods in my package
if if the classes have docstrings.
B:
Pointed Graham to to the visiblename function of pydoc.py, where I 
recently made a small change to get it to display `private' methods, 
and hypothesized that would be where he'd want to start in order to 
modify pydoc to meet his needs.
/context for future thread readers

Before I responded, I tried for a bit to write the code to filter for 
only those objects with docstrings like you wanted. I'm fairly new to 
programming and wasn't able to work out exactly what code is needed. 
(My skill level is such that it isn't quite so straight-forward to me :-)

Would you be willing to post what you did to make it work? I think I'd 
learn something, having bounced off when making a (gentle) push on the 
problem.

Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Vectors in Visual Python

2005-02-24 Thread FLChamp
Thanks for all your help everyone, if only it had addressed what I had
asked I may have actually learned something about Python!!

If anything was addressed to my problem then it has completely passed
me by as most points were clearly made by a computer scientist and I am
not one of those in the slightest. My experience of using any type of
programming language is limited to the little we are taught in my
non-computing subject and hence I have no idea what the below is all
about!! In future example code may be more useful to help newbies like
me :)

That ``speciufication'' (sic) is no more ``a declaration'' than any
other parameter you can pass to a constructor (or any other factory
callable).

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


Re: arrow keys bug

2005-02-24 Thread Daniel Alexandre
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
Hi there,
On Feb 24, 2005, at 16:25, A.T. Hofkamp wrote:
and for home, end, etc. Does anyone here knows how I can strip those
keys? Thanks in advance.
One solution is to read the input yourself character by character, and
delete anything that is not printable.
Another solution may be to prevent sending non-ASCII to the server, ie 
check
such things after enter is pressed.
Thanks for your quick answer, however I'm not sure how I can do any of 
those things.
I would appreciate if you could tell me how to do that, give-me a link 
to a how-to about
that or the location of that in the python-docs, as I can't seem to 
find anything about that.
Thanks in advance.

- -- 
Best Regards,
Daniel Alexandre ( [EMAIL PROTECTED] )
PGP Public Key: http://student.dei.uc.pt/~dfcruz/pubring.html
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.4 (Darwin)

iD8DBQFCHgw3L3+DjgQV3LgRAuoUAJ4rxaQ2Ll/Z4Jge4cakpqmIwWtRuACfd/l7
Gc+P1TlZxPJFh0qhKWCerOo=
=j+Yb
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


update images inside a mysql database

2005-02-24 Thread Jonas Meurer
hello,

i develop a project with a mysql interface. one mysql table holds all
the images for my project.

everything works quite well so far, except i'm not able to upload images
into the database. the following function does the mysql UPDATE, it
requires the image and the image ID as arguments.

additionally it dumps the image to my filesystem ('/tmp/image.gif') -
i test this with gif images.

for some reason, the file dumped to /tmp/image.gif is exactly the same
as uploaded, but in mysql the file is corrupted, far to small and not
even viewable.

here is my function:

def i_update(image, imgid):
image = %s % (image)
sql_exec = UPDATE Images SET Image='%s' WHERE ImgID = '%s'
 % (image, imgid)
o = open(/tmp/file.jpg, w)
o.write(image)
o.close()
db_connect.cursor.execute(sql_exec)


i've the strong feeling that the substitution makes problems. if the
string 'image' conains ' or  for example, the sql_exec is broken.

what do you suggest?

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


Re: what is wrong?

2005-02-24 Thread neutrinman
I appreciate all of your help.
I learned a lot form your adovice.
Thanks.

Mr. Bieber, it worked fine. Thanks again.

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


Re: Shift Confusion

2005-02-24 Thread James Kew
Dennis Lee Bieber [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 On 23 Feb 2005 22:06:54 -0800, Kamilche [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:


 Essentially, it should be possible to use a 'packed string' format in
 Python, where as long as the characters you're sending are in the ASCII
 range 0 to 127, two will fit in a byte.

 Pardon? You are going to fit TWO 7-bit values into one 8-bit?

Quite. Although you can sort of see how one might naively arrive at this 
conclusion: one 7-bit char takes 0...127, which when you put it into an 
8-bit byte leaves 128...255 unused for a second char

James


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


Re: Need some Python help

2005-02-24 Thread Roger Upole
There's a bug in python's tokenizer that's triggered when
the generated wrapper code for a COM object has
lines longer than 512.  See below link for a workaround:

https://sourceforge.net/tracker/?func=detailatid=551954aid=1085454group_id=78018

   Roger


Matt Upton [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]


 Hello, I am new to Python and am trying to produce script to run batch
 processes for ArcGIS 9.0 (ArcView).  I have upgraded to Phython 2.4 from 
 2.1
 and am using the Pythonwin to try to code but am running into a problem.
 Whenever I try to debug my program or run any code past the following code
 it gets hung up and crashes, quits, no warning, and no messages.  HELP, 
 what
 is the problem, it is getting very frustrating.

 import win32com.client
 gp = win32com.client.Dispatch(esriGeoprocessing.GPDispatch.1)
 gp.workspace = c:/Program Files/ArcGIS/NASA


 It ALWAYS crashes and quits 30 sec or so after line 2 or 3 of the code
 above  I can't get Python to do anything in ArcGIS so far, none of the
 tools can be called or used?

 I am assuming there is some sort of path or link that is not working
 properly between ArcGIS and Python?

 Using the same coding in the IDLE Python environment results in the same
 crashing results.

 Oh yea, I am running everything on Windows XP.

 Thank you.

 Matthew Upton



 



== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: update images inside a mysql database

2005-02-24 Thread Gabriel Cooper

Jonas Meurer wrote:
def i_update(image, imgid):
   image = %s % (image)
   sql_exec = UPDATE Images SET Image='%s' WHERE ImgID = '%s'
% (image, imgid)
   o = open(/tmp/file.jpg, w)
   o.write(image)
   o.close()
   db_connect.cursor.execute(sql_exec)
I've never tried extensively to use images inside a database (too slow 
for most of my uses), but I thought I'd drop in to point out that you 
should, for security reasons, be using place holders on your sql. It 
might just fix your image problem as well, but I don't know. Also, 
converting a binary image into a string doesn't seem like it would be 
wise, but like I said, I've never tried it. At any rate, your function 
would look like this:

def i_update(image, imgid):
   image = %s % (image)
   o = open(/tmp/file.jpg, w)
   o.write(image)
   o.close()
   db_connect.cursor.execute(UPDATE Images SET Image=%s WHERE ImgID=%s, 
  (image, imgid))

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


Re: Trouble with mysql-python 1.2.0 on Solaris 8 sparc

2005-02-24 Thread Steve Holden
Alec Wysoker wrote:
Hi Andy,
Thanks for your message.  It turned out that I had installed 64-bit
mySql on a 32-bit machine.  I'm amazed it worked at all.  Anyway, I
finally got mysql-python built, but I'm unable to connect to a machine
on a remote host.  The problem doesn't seem to be with the python code,
because I'm unable to do it even with the mysql command-line client.
Sigh.
Could be you have a 4.2 server and an earlier client. Unbelievably, 
MySQL changed its protocol while only incrementing the minor version 
number, and this bit me in the ass when I wanted to move up to 4.1.

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


[ANN] dateutil 0.9

2005-02-24 Thread Gustavo Niemeyer

https://moin.conectiva.com.br/DateUtil


Description
---

The dateutil module provides powerful extensions to
the standard datetime module, available in Python 2.3+.


Features


- Computing of relative deltas (next month, next year,
  next monday, last week of month, etc);

- Computing of relative deltas between two given
  date and/or datetime objects;

- Computing of dates based on very flexible recurrence rules,
  using a superset of the iCalendar specification. Parsing of RFC
  strings is supported as well.

- Generic parsing of dates in almost any string format;

- Timezone (tzinfo) implementations for tzfile(5) format
  files (/etc/localtime, /usr/share/zoneinfo, etc), TZ
  environment string (in all known formats), iCalendar
  format files, given ranges (with help from relative deltas),
  local machine timezone, fixed offset timezone, UTC timezone,
  and Windows registry-based time zones.

- Internal up-to-date world timezone information based on
  Olson's database.

- Computing of Easter Sunday dates for any given year,
  using Western, Orthodox or Julian algorithms;

- More than 400 test cases.


Version 0.9
---

- Implemented internal timezone information with binary
  timezone files [1]. datautil.tz.gettz() function will now
  try to use the system timezone files, and fallback to
  the internal versions. It's also possible to ask for
  the internal versions directly by using
  dateutil.zoneinfo.gettz().

- New tzwin timezone type, allowing access to Windows
  internal timezones (contributed by Jeffrey Harris).

- Fixed parsing of unicode date strings.

- Fixed pickling of timezone types, as reported by
  Andreas Köhler.

- Accept parserinfo instances as the parser constructor
  parameter, besides parserinfo (sub)classes.

- Changed weekday to spell the not-set n value as None
  instead of 0.

- Fixed other reported bugs.

[1] http://www.twinsun.com/tz/tz-link.htm


-- 
Gustavo Niemeyer
http://niemeyer.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Mapping operator tokens to special methods

2005-02-24 Thread jamesthiele . usenet
I was starting to write a dictionary to map operator strings to their
equivalent special methods such as:
{
  '+' : 'add',
  '' : 'and_'
}

The idea is to build a simple interactive calculator.

and was wondering if there is already something like this builtin?

Or is there a better way to do what I want?

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


[ANN] TamTam collaboration software

2005-02-24 Thread Aleksandar Erkalovic
Hi,
 on address (temporary):
http://tamtam.mi2.hr:/NoviTam/
 you can find TamTam collaborative software. This is new version 
(rewrite) using Twisted and Nevow. This is not official announcement
just a small notice for people who are interested to check it, give me 
some critics, help in ideas or maybe help in development.

Aco
--
http://aco.mi2.hr/
--
http://mail.python.org/mailman/listinfo/python-list


Interesting decorator use.

2005-02-24 Thread Scott David Daniels
I have started doing the following to watch for exceptions in wxPython.
I'd like any input about (A) the interface, and (B) the frame before I
throw it in the recipes book.
import wx, os, sys
errorframe = None
def watcherrors(function):
'''function decorator to display Exception information.'''
def substitute(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception:
error_type, error, traceback = sys.exc_info()
mb = wx.MessageDialog(errorframe,
'%s\n\nClick OK to see traceback' % error,
'Error in Run',
wx.OK | wx.CANCEL | wx.ICON_ERROR)
if wx.ID_OK == mb.ShowModal():
mb.Destroy()
from traceback import extract_tb
trace = ['%s line %s in %s:\n\t%s' % (
 (os.path.splitext(os.path.split(
 name)[1])[0], line, fun, text)
 for name, line, fun, text in
 extract_tb(traceback)]
mb = wx.MessageDialog(errorframe,
'\n'.join(['%s\n' % error] + trace),
'Run Error w/ Traceback',
wx.OK | wx.ICON_ERROR)
result = mb.ShowModal()
mb.Destroy()
raise
if function.__doc__ is not None:
substitute.__doc__ = function.__doc__
return substitute
You can use it as follows to wrap functions and methods:
@watcherrors
def something(somearg)
if somearg is not None:
raise ValueError(somearg)
You can use this by simply placing '@watcherrors' on the line before a
function or method definition.  Some of my questions are:
   A) Is there a better name? Perhaps exceptions or watcher?
   B) Is a global the right way to define the parent of the driven
  message box, or adding another wrapper layer as follows better?
  def exceptionwatcher(base, name):
  def watcherrors(
  ...
  def substitute(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception:
error_type, error, traceback = sys.exc_info()
errorframe = getattr(base, name, None) ### new code
...
  return watcherrors
  Wrapping the code this way allows you to say, watcher-by-watcher,
  where to get the parent for the message box.  You would then use
  it as follows:
@exceptionwatcher(someholder, 'frame')
def something(somearg)
if somearg is not None:
raise ValueError(somearg)
C) Stuff I've not even thought of.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mapping operator tokens to special methods

2005-02-24 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
I was starting to write a dictionary to map operator strings to their
equivalent special methods such as:
{
  '+' : 'add',
  '' : 'and_'
}
The idea is to build a simple interactive calculator.
and was wondering if there is already something like this builtin?
Or is there a better way to do what I want?
There's not already a mapping builtin, but you should definitely look at 
the operator module:

py import operator
py ops = {'+':operator.add, '':operator.and_}
py ops['+'](3, 2)
5
py ops[''](3, 2)
2
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-02-24 Thread Scott David Daniels
Douglas Alan wrote:
...
In any case, as a suggestion to the whomever it is that arranges for
stuff to be put into the standard library, there should be something
like this there, so everyone doesn't have to reinvent the wheel (even
if it's an easy wheel to reinvent) for something that any sysadmin
(and many other users) would want to do on practically a daily basis.
The general model is that you produce a module, and if it gains a
audience to a stable interface, inclusion might be considered.  I'd
suggest you put up a recipe at ActiveState.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-02-24 Thread Christopher De Vries
On Thu, Feb 24, 2005 at 02:03:52PM -0500, Douglas Alan wrote:
 Thanks for the generator.  It returns an extra blank line at the end
 when used with find -print0, which is probably not ideal, and is
 also not how the normal file line iterator behaves.  But don't worry
 -- I can fix it.

Sorry... I forgot to try it with a null terminated string. I guess it further
illustrates the power of writing good test cases. Something like this would
help: 

# yield anything left over
if retain[0]:
yield retain[0]

The other modification would be an option to ignore multiple nulls in a row,
rather than returning empty strings, which could be done in a similar way.

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


Re: Shift Confusion

2005-02-24 Thread Steve Holden
Dennis Lee Bieber wrote:
On Thu, 24 Feb 2005 14:22:59 -, Richard Brodie [EMAIL PROTECTED]
declaimed the following in comp.lang.python:

John Machin [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]

Essentially, it should be possible to use a 'packed string' format in
Python, where as long as the characters you're sending are in the ASCII
range 0 to 127, two will fit in a byte.
It should be possible, but only in a realm where phlogiston and
perpetual motion machines exist.
alt.sys.pdp10 ?
Closest thing I know of to what is being attempted is DEC's
RAD-50; but that was essentially just uppercase A..Z, 0..9, and a few
punctuation marks, and packed three of them into two bytes.
Another code it used was known as SIXBIT, allowing 64 different 
characters. IIRC it could cope with letters, digits and a bunch of 
punctuation - see

  http://nemesis.lonestar.org/reference/telecom/codes/sixbit.html
The DECSystem-10 used a 3-6 bit word, so you could get six sixbit 
characters to a word. In ASCII you could only get four (or, if you threw 
the parity bit away, five) characters to a word.

While its character-handling instructions weren't, as I recall, unique 
in the industry, the DECSystem-10 remains the only hardware I ever got 
to use that had instructions to handle variable byte sizes.

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


Re: Trouble with mysql-python 1.2.0 on Solaris 8 sparc

2005-02-24 Thread Steve Holden
Alec Wysoker wrote:
Hi Steve,
Thanks for the response.  I don't think this is the problem.  When I connect to 
the remote machine, it says this:
Your MySQL connection id is 58 to server version: 4.1.0-alpha-standard
When I connect to the local server, I get this:
Your MySQL connection id is 6 to server version: 4.1.10-standard
One would assume that 4.1.0 and 4.1.10 are compatible, no?
Indeed. Sorry I couldn't be of more assistance. I suspected that the 
MySQLdb driver was somehow compiled with 4.0-or-earlier client software 
- is this possible?

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with mysql-python 1.2.0 on Solaris 8 sparc

2005-02-24 Thread Alec Wysoker
Do you mean the python glue code?  I am having this problem when python is not 
in the picture at all, just running mysql command-line client.  Presumably my 
client is 4.1.10, as it came in a built package along with the 4.1.10 server.  
In fact, the following seems to indicate that it is the right version:

/usr/local/mysql/bin/mysql --version
/usr/local/mysql/bin/mysql  Ver 14.7 Distrib 4.1.10, for sun-solaris2.8 (sparc)


At 03:08 PM 2/24/2005, Steve Holden wrote:
Alec Wysoker wrote:

Hi Steve,
Thanks for the response.  I don't think this is the problem.  When I connect 
to the remote machine, it says this:
Your MySQL connection id is 58 to server version: 4.1.0-alpha-standard
When I connect to the local server, I get this:
Your MySQL connection id is 6 to server version: 4.1.10-standard
One would assume that 4.1.0 and 4.1.10 are compatible, no?
Indeed. Sorry I couldn't be of more assistance. I suspected that the MySQLdb 
driver was somehow compiled with 4.0-or-earlier client software - is this 
possible?

regards
 Steve
-- 
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/



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


Re: Interesting decorator use.

2005-02-24 Thread Tom Willis
On Thu, 24 Feb 2005 11:15:07 -0800, Scott David Daniels
[EMAIL PROTECTED] wrote:
 
 I have started doing the following to watch for exceptions in wxPython.
 I'd like any input about (A) the interface, and (B) the frame before I
 throw it in the recipes book.
 
  import wx, os, sys
  errorframe = None
 
  def watcherrors(function):
  '''function decorator to display Exception information.'''
  def substitute(*args, **kwargs):
...

Pretty cool.

Question on decorators in general. Can you parameterize those?

If I wanted to something and after the function call for example, I
would expect something like this would work.

def prepostdecorator(function,pre,post):
def wrapper(*args,**kwargs):
pre()
result =  function(*args,**kwargs)
post()
return result
return wrapper

def dopre():
print call pre

def dopost():
print call post

@prepostdecorator(pre,post)
def sayhello(Name):
print Hey %s, nice to meet you % Name

#sayhello = prepostdecorator(sayhello,dopre,dopost)

if __name__==__main__:
sayhello(Dude)



but I get ...
TypeError: prepostdecorator() takes exactly 3 arguments (2 given)


Where as 

def prepostdecorator(function,pre,post):
def wrapper(*args,**kwargs):
pre()
result =  function(*args,**kwargs)
post()
return result
return wrapper

def dopre():
print call pre

def dopost():
print call post

def sayhello(Name):
print Hey %s, nice to meet you % Name

sayhello = prepostdecorator(sayhello,dopre,dopost)

if __name__==__main__:
sayhello(Dude)

#outputs
call pre
Hey Dude, nice to meet you
call post

Does what I want.


I guess I'm having problems with how function get's in there similair
to how self magically gets in a method, except when you specify other
params. Got linky?



-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-02-24 Thread John Machin
On Thu, 24 Feb 2005 11:53:32 -0500, Christopher De Vries
[EMAIL PROTECTED] wrote:

On Wed, Feb 23, 2005 at 10:54:50PM -0500, Douglas Alan wrote:
 Is there a canonical way of iterating over the lines of a file that
 are null-separated rather than newline-separated?

I'm not sure if there is a canonical method, but I would recommending using a
generator to get something like this, where 'f' is a file object:

def readnullsep(f):
# Need a place to put potential pieces of a null separated string
# across buffer boundaries
retain = []

while True:
instr = f.read(2048)
if len(instr)==0:
# End of file
break

# Split over nulls
splitstr = instr.split('\0')

# Combine with anything left over from previous read
retain.append(splitstr[0])
splitstr[0] = ''.join(retain)

# Keep last piece for next loop and yield the rest
retain = [splitstr[-1]]
for element in splitstr[:-1]:

(1) Inefficient (copies all but the last element of splitstr)

yield element

# yield anything left over
yield retain[0]

(2) Dies when the input file is empty.

(3) As noted by the OP, can return a spurious empty line at the end.

Try this:

!def readweird(f, line_end='\0', bufsiz=8192): 
!retain = '' 
!while True: 
!instr = f.read(bufsiz)
!if not instr:
!# End of file 
!break 
!splitstr = instr.split(line_end)
!if splitstr[-1]:
!# last piece not terminated
!if retain:
!splitstr[0] = retain + splitstr[0]
!retain = splitstr.pop()
!else:
!if retain:
!splitstr[0] = retain + splitstr[0]
!retain = ''
!del splitstr[-1]
!for element in splitstr: 
!yield element 
!if retain:
!yield retain

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


Re: Mapping operator tokens to special methods

2005-02-24 Thread John Machin
On 24 Feb 2005 10:57:58 -0800, [EMAIL PROTECTED] wrote:

I was starting to write a dictionary to map operator strings to their
equivalent special methods such as:
{
  '+' : 'add',
  '' : 'and_'
}

The idea is to build a simple interactive calculator.

and was wondering if there is already something like this builtin?

 eval('1+2')
3


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


More newbie macosx user questions

2005-02-24 Thread Timothy Grant
I think I'm mis-understanding something about how PYTHONPATH works (at
least on OSX I didn't have this trouble on Linux).

I have a directory where I store libraries that I'm playing around
with. However, for some reason python can't find the library. Since
I'm using PyQt, I use pythonw, but the results are identical with
python. It doesn't look like my PYTHONPATH is getting prepended to the
library path.

Can anyone tell me what I'm doing wrong?

([EMAIL PROTECTED]) echo $PYTHONPATH 
/Users/timothygrant/code/lib
([EMAIL PROTECTED]) ls $PYTHONPATH
NJB.pyNJB.pyc   _njb_c.so njb_c.py  njb_c.pyc
([EMAIL PROTECTED]) pythonw
Python 2.3 (#1, Sep 13 2003, 00:49:11) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type help, copyright, credits or license for more information.
 import NJB
Traceback (most recent call last):
  File stdin, line 1, in ?
ImportError: No module named NJB
 import sys
 for p in sys.path:
... print p
... 

/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python23.zip
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-dynload
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mapping operator tokens to special methods

2005-02-24 Thread jamesthiele . usenet
John Machin wrote:
 eval('1+2') 

3 
--
Yeah, that's what I decided to do.

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


Re: Python and Ajax technology collaboration

2005-02-24 Thread Chris
Does anyone else have any Nevow examples?


In article [EMAIL PROTECTED], 
[EMAIL PROTECTED] says...
 aurora [EMAIL PROTECTED] wrote:
 
  It was discussed in the last Bay Area Python Interest Group meeting.
  
  Thursday, February 10, 2005
  Agenda: Developing Responsive GUI Applications Using HTML and HTTP
  Speakers: Donovan Preston
  http://www.baypiggies.net/
  
  The author has a component LivePage for this. You may find it from  
  http://nevow.com/. Similar idea from the Javascript stuff but very Python
  centric.
 
 As an example for that technology (LivePage) I have this:
 
 http://vercingetorix.dyndns.org:20080/
 
 Which is an online forum where the Quote  Reply function is done with
 XMLHttpRequest and Python.
 
 Implementing this stuff in the forum with Nevow ( the framework created
 by Donovan who I help to develop ) was almost effortless. 
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] exercise: partition a list by equivalence

2005-02-24 Thread Paul McGuire
A slightly better version, only walks the set of cumulative list of
sets once per pairing.

-- Paul

.import sets
.
.input = [[1, 2], [3, 4], [2, 3], [4, 5]]
.input = [[1, 2], [3, 4], [4, 5]]
.input = [[1, 2],[2,1], [3, 4], [4, 5],[2,2],[2,3],[6,6]]
.
.def merge(pairings):
.ret = []
.for a,b in pairings:
.aset = None
.bset = None
.for s in ret:
.if not aset and a in s:
.aset = s
.if not bset and b in s:
.bset = s
.if aset and bset:
.break
.else:
.if aset:
.aset.add(b)
.elif bset:
.bset.add(a)
.else:
.ret.append(sets.Set([a,b]))
.continue
.if aset is not bset:
.ret.remove(aset)
.ret.remove(bset)
.ret.append(aset.union(bset))
.
.return [list(s) for s in ret]
.
.print merge(input)

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


Re: Interesting decorator use.

2005-02-24 Thread Steven Bethard
Tom Willis wrote:
Question on decorators in general. Can you parameterize those?
If I wanted to something and after the function call for example, I
would expect something like this would work.
def prepostdecorator(function,pre,post):
def wrapper(*args,**kwargs):
pre()
result =  function(*args,**kwargs)
post()
return result
return wrapper
def dopre():
print call pre
def dopost():
print call post
@prepostdecorator(pre,post)
def sayhello(Name):
print Hey %s, nice to meet you % Name
#sayhello = prepostdecorator(sayhello,dopre,dopost)
if __name__==__main__:
sayhello(Dude)
but I get ...
TypeError: prepostdecorator() takes exactly 3 arguments (2 given)
You get this TypeError for the same reason that I get the following 
TypeError:

py def prepostdecorator(function, pre, post):
... pass
...
py prepostdecorator(1, 2)
Traceback (most recent call last):
  File interactive input, line 1, in ?
TypeError: prepostdecorator() takes exactly 3 arguments (2 given)
The expression after @ is a _normal Python expression_.  So since you 
couldn't call prepostdecorator with 2 arguments in any other situation, 
you still can't.

If you want to call prepostdecorator with 2 arguments, you need to write 
it this way.  A few options:

(1) Use nested functions:
py def prepostdecorator(pre,post):
... def decorator(function):
... def wrapper(*args,**kwargs):
... pre()
... result =  function(*args,**kwargs)
... post()
... return result
... return wrapper
... return decorator
...
py @prepostdecorator(dopre, dopost)
... def sayhello(name):
... print Hey %s, nice to meet you % name
...
py sayhello('Tom')
call pre
Hey Tom, nice to meet you
call post
(2) Use functional.partial (PEP 309[1])
py def prepostdecorator(pre, post, function):
... def wrapper(*args,**kwargs):
... pre()
... result =  function(*args,**kwargs)
... post()
... return result
... return wrapper
...
py @partial(prepostdecorator, dopre, dopost)
... def sayhello(name):
... print Hey %s, nice to meet you % name
...
py sayhello('Tom')
call pre
Hey Tom, nice to meet you
call post
(3) Use a class:
py class prepostdecorator(object):
... def __init__(self, pre, post):
... self.pre, self.post = pre, post
... def __call__(self, function):
... def wrapper(*args,**kwargs):
... self.pre()
... result = self.function(*args,**kwargs)
... self.post()
... return result
... return wrapper
py @prepostdecorator(dopre, dopost)
... def sayhello(name):
... print Hey %s, nice to meet you % name
...
py sayhello('Tom')
call pre
Hey Tom, nice to meet you
call post
Note that in all of the above cases, the result of evaluating the 
expression after the @ is a callable object that takes _exactly one_ 
argument, the function to be decorated.

HTH,
STeVe
[1] http://www.python.org/peps/pep-0309.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interesting decorator use.

2005-02-24 Thread Steven Bethard
I wrote:
Tom Willis wrote:
Question on decorators in general. Can you parameterize those?

[snip]
If you want to call prepostdecorator with 2 arguments, you need to write 
it this way.  A few options:
Sorry, I forgot my favorite one:
(4) Use a class and functional.partial:
py class prepostdecorator(object):
... def __init__(self, pre, post, function):
... self.pre, self.post, self.function = pre, post, function
... def __call__(self, *args, **kwargs):
... self.pre()
... result = self.function(*args,**kwargs)
... self.post()
... return result
...
py @partial(prepostdecorator, dopre, dopost)
... def sayhello(name):
... print Hey %s, nice to meet you % name
...
py sayhello('Tom')
call pre
Hey Tom, nice to meet you
call post
Woo-hoo, I got rid of all the nested functions!  ;)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: update images inside a mysql database

2005-02-24 Thread Jonas Meurer
On 24/02/2005 Gabriel Cooper wrote:
 I've never tried extensively to use images inside a database (too slow 
 for most of my uses), but I thought I'd drop in to point out that you 
 should, for security reasons, be using place holders on your sql. It 
 might just fix your image problem as well, but I don't know.

i don't know what your example changes with using placeholders, as my
version used placeholders as well. anyway, i changed my code to resemble
your version. i still get the same problem:
(cgitb output)

---SNIP-
 /home/jonas/public_html/inventaria/mods/backend.py in 
i_update(image='\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00\xff\xdb\x00C\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01...#$\x82\x08f\xe5A\xc6\xe2G\xe4I\xa9\x18\x96.\xa7\x18T\x0e\x08\xe0\x92q\x9c\x9e\xa4s\xd3\xb7j(\xa0\n\xa4\x95\x00\x03\xdd\x87\xafC\
xefE\x14P\x07\xff\xd9', imgid='18')
  259 o.write(image)
  260 o.close()
  261 db_connect.cursor.execute(UPDATE Images SET Image=%s WHERE
  262 ImgID = %s % (image, imgid))
  263
global db_connect = module 'db_connect' from 'mods/db_connect.pyc',
db_connect.cursor = MySQLdb.cursors.Cursor object,
db_connect.cursor.execute = bound method Cursor.execute of 
MySQLdb.cursors.Cursor object, image = 
'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00\xff\xdb\x00C\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01...#$\x82\x08f\xe5A\xc6\xe2G\xe4I\xa9\x18\x96.\xa7\x18T\x0e\x08\xe0\x92q\x9c\x9e\xa4s\xd3\xb7j(\xa0\n\xa4\x95\x00\x03\xdd\x87\xafC\xefE\x14P\x07\xff\xd9',
 imgid = '18'

 /usr/lib/python2.3/site-packages/MySQLdb/cursors.py in 
execute(self=MySQLdb.cursors.Cursor object, query='UPDATE Images SET 
Image=\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00\xff\xdb\x00C...\xe0\x92q\x9c\x9e\xa4s\xd3\xb7j(\xa0\
 n\xa4\x95\x00\x03\xdd\x87\xafC\xefE\x14P\x07\xff\xd9 WHERE\n\t\t\t\tImgID = 
18', args=None)
   93 
   94 del self.messages[:]
   95 return self._execute(query, args)
   96
   97 def _execute(self, query, args):
self = MySQLdb.cursors.Cursor object, self._execute = bound method 
Cursor._execute of MySQLdb.cursors.Cursor object, query = 'UPDATE Images SET 
Image=\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00\xff\xdb\x00C...\xe0\x92q\
 
x9c\x9e\xa4s\xd3\xb7j(\xa0\n\xa4\x95\x00\x03\xdd\x87\xafC\xefE\x14P\x07\xff\xd9 
WHERE\n\t\t\t\tImgID = 18', args = None

[...]

 /usr/lib/python2.3/site-packages/MySQLdb/connections.py in 
defaulterrorhandler(connection=_mysql.connection open to 'localhost' at 
691500, cursor=MySQLdb.cursors.Cursor object, errorclass=class 
_mysql_exceptions.OperationalError, 
errorvalue=_mysql_exceptions.OperationalError instance)
   31 else:
   32 connection.messages.append(error)
   33 raise errorclass, errorvalue
   34
   35
errorclass = class _mysql_exceptions.OperationalError, errorvalue = 
_mysql_exceptions.OperationalError instance

 OperationalError: (1054, Unknown column 
'\xff\xd8\xff\xe0' in 'field list')
 args = (1054, Unknown column 
'\xff\xd8\xff\xe0' in 'field list')
---SNIP-
the problem is obviously, that the 'string' Image contains characters
that make it end ealier than expected.

 converting a binary image into a string doesn't seem like it would be 
 wise, but like I said, I've never tried it. At any rate, your function 
 would look like this:

i've been told on #python that unix doesn't differ between binary and
ascii, thus storing binary data should be no problem.

i've no glue about how to solve this problem. even if i use quotation
marks of any kind for the mysql values, what sometimes circumvents the
problem above, at best some some 1000 byte big blob is stored in the
mysql database, what is neither an image nor has the size of my uploaded
image.

any suggestions?

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


Re: Interesting decorator use.

2005-02-24 Thread Tom Willis
On Thu, 24 Feb 2005 15:00:46 -0700, Steven Bethard
[EMAIL PROTECTED] wrote:
 Tom Willis wrote:
  Question on decorators in general. Can you parameterize those?
 
  If I wanted to something and after the function call for example, I
  would expect something like this would work.
 
  def prepostdecorator(function,pre,post):
  def wrapper(*args,**kwargs):
  pre()
  result =  function(*args,**kwargs)
  post()
  return result
  return wrapper
 
  def dopre():
  print call pre
 
  def dopost():
  print call post
 
  @prepostdecorator(pre,post)
  def sayhello(Name):
  print Hey %s, nice to meet you % Name
 
  #sayhello = prepostdecorator(sayhello,dopre,dopost)
 
  if __name__==__main__:
  sayhello(Dude)
 
  but I get ...
  TypeError: prepostdecorator() takes exactly 3 arguments (2 given)
 
 You get this TypeError for the same reason that I get the following
 TypeError:
 
 py def prepostdecorator(function, pre, post):
 ... pass
 ...
 py prepostdecorator(1, 2)
 Traceback (most recent call last):
File interactive input, line 1, in ?
 TypeError: prepostdecorator() takes exactly 3 arguments (2 given)
 
 The expression after @ is a _normal Python expression_.  So since you
 couldn't call prepostdecorator with 2 arguments in any other situation,
 you still can't.
 
 If you want to call prepostdecorator with 2 arguments, you need to write
 it this way.  A few options:
 
 (1) Use nested functions:
 
 py def prepostdecorator(pre,post):
 ... def decorator(function):
 ... def wrapper(*args,**kwargs):
 ... pre()
 ... result =  function(*args,**kwargs)
 ... post()
 ... return result
 ... return wrapper
 ... return decorator
 ...
 py @prepostdecorator(dopre, dopost)
 ... def sayhello(name):
 ... print Hey %s, nice to meet you % name
 ...
 py sayhello('Tom')
 call pre
 Hey Tom, nice to meet you
 call post
 
 (2) Use functional.partial (PEP 309[1])
 
 py def prepostdecorator(pre, post, function):
 ... def wrapper(*args,**kwargs):
 ... pre()
 ... result =  function(*args,**kwargs)
 ... post()
 ... return result
 ... return wrapper
 ...
 py @partial(prepostdecorator, dopre, dopost)
 ... def sayhello(name):
 ... print Hey %s, nice to meet you % name
 ...
 py sayhello('Tom')
 call pre
 Hey Tom, nice to meet you
 call post
 
 (3) Use a class:
 
 py class prepostdecorator(object):
 ... def __init__(self, pre, post):
 ... self.pre, self.post = pre, post
 ... def __call__(self, function):
 ... def wrapper(*args,**kwargs):
 ... self.pre()
 ... result = self.function(*args,**kwargs)
 ... self.post()
 ... return result
 ... return wrapper
 py @prepostdecorator(dopre, dopost)
 ... def sayhello(name):
 ... print Hey %s, nice to meet you % name
 ...
 py sayhello('Tom')
 call pre
 Hey Tom, nice to meet you
 call post
 
 Note that in all of the above cases, the result of evaluating the
 expression after the @ is a callable object that takes _exactly one_
 argument, the function to be decorated.
 
 HTH,
 
 STeVe
 
 [1] http://www.python.org/peps/pep-0309.html
 --
 http://mail.python.org/mailman/listinfo/python-list
 
Wow thanks for the explanation!! Some of it is a bit mind bending to
me at the moment , but I'm going to mess with it a bit.



-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Online Programming Contest

2005-02-24 Thread Will Stuyvesant
 [Varun]
 For details about samhita http://www.samhita.info/

The Madras Institute of Technology (MIT) it says there.

The MIT acronym is taken already guys..

-- 
no scheme no glory

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


Re: Python Online Programming Contest

2005-02-24 Thread Terry Reedy

Varun [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hi Friends,
 Department of Information Technology, Madras Institute of Technology,
 Anna University, India
 is conducting a technical symposium, Samhita. As a part of samhita, an
 Online Programming Contest is scheduled on Sunday, 27 Feb 2005.

Looks like a fun symposium.

 This is the first Online Programming Contest in India to support
 Python .
 Other languages supported are C and C++.

 For Registration and Rules of the contest, http://www.samhita.info/opc

Is this open worldwide or India residents only?
I could not find a time, either local or UTC.

 For details about samhita http://www.samhita.info/

Terry J. Reedy



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


Re: Interesting decorator use.

2005-02-24 Thread Steven Bethard
Tom Willis wrote:
Question on decorators in general. Can you parameterize those?
Wow thanks for the explanation!! Some of it is a bit mind bending to
me at the moment , but I'm going to mess with it a bit.
Oh, I also should have mentioned that there's some explanation at:
http://www.python.org/peps/pep-0318.html
Specifically on parameterizing:
The current syntax also allows decorator declarations to call a 
function that returns a decorator:

@decomaker(argA, argB, ...)
def func(arg1, arg2, ...):
pass
This is equivalent to:
func = decomaker(argA, argB, ...)(func)
The rationale for having a function that returns a decorator is that the 
part after the @ sign can be considered to be an expression (though 
syntactically restricted to just a function), and whatever that 
expression returns is called. See declaration arguments [15].

But playing around with it is, IMHO, definitely the best way to figure 
it out. =)

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


Re: pyGoogle is fun and easy to use, and thinks Python is the best programming language

2005-02-24 Thread Andy Robinson
Regrettably, inserting Visual Basic into the list produces a
different winner.  I think you want some very subtle hard coding which
limits it to on-space-delimited languages :-(

- Andy

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


Re: Python and Ajax technology collaboration

2005-02-24 Thread Valentino Volonghi aka Dialtone
Chris [EMAIL PROTECTED] wrote:

 Does anyone else have any Nevow examples?

Nevow SVN is full of examples ranging from a simple hello world to a
complete blog engine with xml-rpc, smtp and web interfaces for adding
new posts and an atom feed, or even a live chat or a pastebin or an
image uploader and so on.

-- 
Valentino Volonghi aka Dialtone
Now Running MacOSX 10.3.8
Blog: http://vvolonghi.blogspot.com
http://weever.berlios.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Ajax technology collaboration

2005-02-24 Thread Evan Simpson
John Willems wrote:
Interesting GUI developments, it seems. Anyone developed a Ajax
application using Python? Very curious
Not what you meant, perhaps, but http://weboggle.shackworks.com has a 
Javascript/HTML/CSS one-page client that uses XMLHttpRequest to talk to 
a Python back-end.  The requests are very crude, though, and the server 
is utterly specialized (no framework, not even asyncore).

Cheers,
Evan @ 4-am
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Online Programming Contest

2005-02-24 Thread Kartic
Will Stuyvesant said the following on 2/24/2005 5:10 PM:
[Varun]
For details about samhita http://www.samhita.info/

The Madras Institute of Technology (MIT) it says there.
The MIT acronym is taken already guys..
Will - It is a local acronym!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-02-24 Thread John Machin
On Thu, 24 Feb 2005 16:51:22 -0500, Christopher De Vries
[EMAIL PROTECTED] wrote:

[snip]

I think this is a definite improvement... especially putting the buffer size
and line terminators as optional arguments, and handling empty files. I think,
however that the if splitstr[-1]: ... else: ... clauses aren't necessary,

Indeed. Any efficiency gain would be negated by the if test and it's
only once per buffer-full anyway. I left all that stuff in to show
that I had actually analyzed the four cases i.e. it wasn't arrived at
by lucky accident.

 so I
would probably reduce it to this:

[snip]

Popping off that last member and then iterating over the rest of the list as
you suggested is so much more efficient, and it looks a lot better. 

Yeah. If it looks like a warthog, it is a warthog. The converse is of
course not true; examples of elegant insufficiency abound.

Cheers,
John

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


Re: Interesting decorator use.

2005-02-24 Thread Tom Willis
On Thu, 24 Feb 2005 15:20:30 -0700, Steven Bethard
[EMAIL PROTECTED] wrote:
 Tom Willis wrote:
  Question on decorators in general. Can you parameterize those?
 
  Wow thanks for the explanation!! Some of it is a bit mind bending to
  me at the moment , but I'm going to mess with it a bit.
 
 Oh, I also should have mentioned that there's some explanation at:
 
 http://www.python.org/peps/pep-0318.html
 
 Specifically on parameterizing:
 
 The current syntax also allows decorator declarations to call a
 function that returns a decorator:
 
 @decomaker(argA, argB, ...)
 def func(arg1, arg2, ...):
  pass
 
 This is equivalent to:
 
 func = decomaker(argA, argB, ...)(func)
 
 The rationale for having a function that returns a decorator is that the
 part after the @ sign can be considered to be an expression (though
 syntactically restricted to just a function), and whatever that
 expression returns is called. See declaration arguments [15].
 
 But playing around with it is, IMHO, definitely the best way to figure
 it out. =)
 
 STeVe
 --
 http://mail.python.org/mailman/listinfo/python-list
 
 Getting back to your recipe. Through the explanation of how to get
parameters in there, I see how it is possible to get a logger in
there.

Pretty slick that python can have AOP-like features sort of out of the box.


Thanks again, off to check out the link... 




-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: duplicate file finder

2005-02-24 Thread Lowell Kirsh
It looks pretty good, but I'll have to take a better look later. Out of 
curiosity, why did you convert the first spaces to pipes rather than add 
the code as an attachment?

Lowell
Christos TZOTZIOY Georgiou wrote:
On Wed, 23 Feb 2005 01:56:02 -0800, rumours say that Lowell Kirsh
[EMAIL PROTECTED] might have written:

Good idea about hashing part of the file before comparing entire files. 
It will make the script longer but the speed increase will most likely 
make it worth it.

My dupefind module was one of the first modules I wrote in python (it was a
shell script once...), so it's not appropriate to post.  However, rewriting it
was in my RSN list; after your post, I said, what the heck :)
I wouldn't describe it as /clean/ Python code, so any comments on style,
methodology (and of course, bugs!) are mostly welcome.  If you have any ideas
how to make it more Pythonic in style, perhaps we can even send it to ASPN.
On the upside, it's a good demo of Python dynamism and therefore power.
All first spaces are converted to pipe symbols to keep code indents, and sorry
for the assignment operators lacking spacing at the left, but it helped me know
what I meant in C, so I kept the habit in Python.

dupefinder.py -- a module to find duplicate files.
find_duplicate_files(*paths):
.   A function returning an iterable of lists of duplicate files
.   To be used as
.   for duplicate_files in dupefinder.find_duplicate_files(dir1, dir2...):
.   # process every group of duplicates

import os, md5, errno, sys
IGNORED_ERROR_CODES= frozenset( [errno.EACCES, errno.ENOENT] )
class File(object):
.   A wrapper for files to facilitate their comparison.
.   
.   Interface:
.   -   .get_hash(level) returns appropriate key for the current cmp level
.   -   .filename
.   -   .size

.   __slots__= filename, size, _hashes,
.   def __init__(self, filename):
.   self.filename= filename
.   self.size= os.path.getsize(filename)
.   if self.size == 0:
.   self._hashes= [0, None, None]
.   else:
.   self._hashes= [self.size]
.   def __repr__(self):
.   return %s('%s') % (self.__class__.__name__, self.filename)
.   def get_hash(self, level):
.   Return appropriate key for level of comparison.
.   level == 0 returns file size
.   level == 1 returns hash of first few kb
.   level == 2 returns md5 sum of whole file
.   if level = len(self._hashes):
.   if 1 = len(self._hashes):
.   self._hashes.append(self._get_partial_hash())
.   if 2 = len(self._hashes):
.   self._hashes.append(self._get_full_hash())
.   return self._hashes[level]
.   def _get_partial_hash(self):
.   fp= open(self.filename)
.   try:
.   return hash(fp.read(8192))
.   finally:
.   fp.close()
.   def _get_full_hash(self):
.   fp= open(self.filename, rb)
.   full_hash= md5.new()
.   while 1:
.   data= fp.read(65536)
.   if not data: break
.   full_hash.update(data)
.   fp.close()
.   return full_hash.digest()
class GenericFilesDict(dict):
.   A virtual wrapper for the dictionaries of file comparisons.
.   Not to be used on its own, but through subclassing.
.   
.   Each subclass should define a _level class attribute to be used with the
.   File.get_hash method, and a _next_class attribute pointing to the class
.   managing the next level comparisons.
.   __slots__= ()

.   def add_file(self, fileobj):
.   Add a File object to self keyed by the appropriate key based on
.   self._level. If another file object exists in the same spot, replace it
.   by a _next_level_class instance containing the pre-existing and new file
.   obj.
.   this_hash= fileobj.get_hash(self._level)
.   try:
.   result = self[this_hash]
.   except KeyError:
.   self[this_hash]= fileobj
.   return
.   try: # there was something in slot [this_hash]
.   result.add_file(fileobj) # so add fileobj to it
.   except AttributeError: # it has no add_file method, so it's a File
.   _= self[this_hash]= self._next_class() # make an instance
.   _.add_file(result) # add pre-existing
.   _.add_file(fileobj) # add new
.   def __repr__(self):
.   return %s%s % (self.__class__.__name__, dict.__repr__(self))
.   def __iter__(self):
.   Return all instances of SameFiles (subclass of list).
.   for item, value in self.iteritems():
.   try: _next_class= value._next_class
.   except AttributeError: continue
.   if _next_class is None:
.   yield value
.   else:
.   for item in value:
.   yield item
class SameFiles(list):
.   A list of duplicate files.
.   __slots__= ()
.   _level= 3
.   _next_class= None # search stops here
.   def add_file(self, fileobj):
.   self.append(fileobj)
class FilesByFullHash(GenericFilesDict):
.   A dictionary keyed on md5 hash of whole file.
.   The 

Nevow examples

2005-02-24 Thread Travis Oliphant
There was a request for nevow examples.  Nevow is a fantastic 
web-development framework for Python.

I used nevow to create http://www.scipy.org/livedocs/
This site uses nevow and self introspection to produce (live) 
documentation for scipy based on the internal docstrings.   It would be 
nice to add the capability for users to update the documentation through 
the web-site.  But, that functionality is not complete.

The code itself is available in the util directory of scipy which can be 
checked out of CVS (or browsed).  Go to http://www.scipy.org  for mor 
details.

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


Re: searching pdf files for certain info

2005-02-24 Thread Follower
rbt [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 Not really a Python question... but here goes: Is there a way to read 
 the content of a PDF file and decode it with Python? I'd like to read 
 PDF's, decode them, and then search the data for certain strings.

I've had success with both:

  http://www.boddie.org.uk/david/Projects/Python/pdftools/

  http://www.adaptive-enterprises.com.au/~d/software/pdffile/pdffile.py

although my preference is for the latter as it transparently handles
decryption. (I've previously posted an enhancement to the `pdftools`
utility that adds decryption handling to it, but now use the `pdffile`
library as it handles it better.)

The ease of text extraction depends a lot on how the PDFs have been
created.

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


Converting HTML to ASCII

2005-02-24 Thread gf gf
Hi.  I'm looking for a Python lib to convert HTML to
ASCII.  Of course, a quick Google search showed
several options (although, I must say, less than I
would expect, considering how easy this is to do in
*other* languages... :| ), but, I have 2 requirements,
which none of them seem to meet:

1) Be able to handle badly formed, or illegal, HTML,
as best as possible.  Some of the converters I tried
ended up dieing on a weird character (that is, a high
ascii char).  Others somehow got confused and dumped
the JavaScript as well.

2) Not embellish the text in any way - no asterisks,
no bracket links, no __ for underlines.

Can anyone direct me to something which could help me
for this?

--Thanks a mil.



__ 
Do you Yahoo!? 
Yahoo! Mail - Helps protect you from nasty viruses. 
http://promotions.yahoo.com/new_mail
-- 
http://mail.python.org/mailman/listinfo/python-list


Best IDe

2005-02-24 Thread Jubri Siji
Please i am new to python , whats the best IDE to start with 


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


Re: Python Online Programming Contest

2005-02-24 Thread Harlin Seritt
Actually MIT is an abbreviation and not an acronym in the true sense of
the word :)

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


Re: Best IDe

2005-02-24 Thread Harlin Seritt
IDLE, PytonWin and SPE are all free and offer all of the important
features you'll see even in commercial IDE's.

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


web status display for long running program

2005-02-24 Thread Brian Roberts
I have a command line Python program that sometimes takes a bit
(several minutes) to run.  I want to provide an optional method for an
impatient user (me!) to check the status of the program.  The type and
amount of status information doesn't fit nicely into a --verbose or
logger -- either too little or too much information at different
points.

I think an optional web page would be convenient interface.  The
Python program would listen on some port, and if queried (by me
browsing to localhost:12345 for example) would return a pretty status
display.  Hitting reload would update the status etc.

My problem is that I'm not sure how to do this:
- I don't want to embed a full web server into the application or
require any special PC setup.
- I think I know how to listen on a socket, but not sure how to send
stuff to to a web browser -- just start with HTML?  Or like a CGI
script with the header stuff like text/html?  (I don't care if I have
to write the HTML by hand or can use a toolkit -- not important).
- Do I need a separate thread to listen and send the HTML?  The
application is currently single threaded.  I'm confortable with
threads, but would prefer to avoid them if possible.

Or is there a better/different way of doing this?  Any general advice
or pointers to some code that already does this would be very much
appreciated.

Python 2.3, under both Linux  Windows if that makes a difference.

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


Re: user interface for python

2005-02-24 Thread Peter Hansen
Mike Meyer wrote:
There are no portable programs, only ported programs.
   -- John Gilmore (?)
This doesn't really ring true, unless one insists on defining
portable to include the idea of universally.
I've got dozens of Python utilities that run equally well
on my Linux machines and my Windows machines.  I didn't
port them, I just wrote them in Python and put them in
both places.
Maybe I'm missing the point of Gilmore's comment...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] generic equivalence partition

2005-02-24 Thread Bryan
Xah Lee wrote:
another functional exercise with lists.
Here's the perl documentation. I'll post a perl and the translated
python version in 48 hours.
=pod
parti(aList, equalFunc)
given a list aList of n elements, we want to return a list that is a
range of numbers from 1 to n, partition by the predicate function of
equivalence equalFunc. (a predicate function is a function that
takes two arguments, and returns either True or False.)
Note: a mathematical aspect: there are certain mathematical constraints
on the a function that checks equivalence. That is to say, if a==b,
then b==a. If a==b and b==c, then a==c. And, a==a. If a equivalence
function does not satisfy these, it is inconsistent and basically give
meaningless result.
example:
parti([['x','x','x','1'],
['x','x','x','2'],
['x','x','x','2'],
['x','x','x','2'],
['x','x','x','3'],
['x','x','x','4'],
['x','x','x','5'],
['x','x','x','5']], sub {$_[0]-[3] == $_[1]-[3]} )
returns
 [[1],['2','3','4'],['5'],['6'],['7','8']];
=cut
In the example given, the input list's elements are lists of 4
elements, and the equivalence function is one that returns True if the
last item are the same.
Note that this is a generic function. The input can be a list whose
elements are of any type. What parti does is to return a partitioned
range of numbers, that tells us which input element are equivalent to
which, according to the predicate given. For example, in the given
example, it tells us that the 2nd, 3rd, 4th elements are equivalent.
And they are equivalent measured by the predicate function given, which
basically tests if their last item are the same integer. (note that if
we want to view the result as indexes, then it is 1-based index. i.e.
counting starts at 1.)
PS if you didn't realize yet, nested lists/dictionaries in perl is a
complete pain in the ass.
PS note that the code sub {$_[0]-[3] == $_[1]-[3]} is what's called
the lambda form, in Perl.
 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html
this is the first thing that came to my mind.  i'm sure there are more clever 
ways to do this.

elements = [['x', 'x', 'x', '1'],
['x', 'x', 'x', '2'],
['x', 'x', 'x', '2'],
['x', 'x', 'x', '2'],
['x', 'x', 'x', '3'],
['x', 'x', 'x', '4'],
['x', 'x', 'x', '5'],
['x', 'x', 'x', '5']]
pos = {}
for i, element in enumerate(elements):
pos.setdefault(element[-1], []).append(i+1)
p = pos.values()
p.sort()
[[1], [2, 3, 4], [5], [6], [7, 8]]
bryan
--
http://mail.python.org/mailman/listinfo/python-list


Re: A few q's on python files.

2005-02-24 Thread Peter Hansen
Tim Roberts wrote:
There are packages (like py2exe) that can convert your script into an
executable, but they are essentially installers.  They package your script,
and all the scripts and libraries it needs, into a single file along with
the interpreter.  When the .exe is executed, it extracts the interpreter
and the scripts into a temp directory, and fires up the interpreter.
Correction: py2exe doesn't really do that at all.  At least,
not any of the single file or extracting stuff.
Py2exe packages all the Python bytecode into a single zip
file (library.zip) and also includes all .pyd and .dll
files required to run the program, along with a stub
.exe file which instantiates an interpreter (from pythonXX.dll)
and runs the main script.
Installers such as InnoSetup are what you use to do the
single file stuff, and when you run them they do the
usual Windows installer stuff like extracting files to the
installation directory, creating icons, etc.
Finally there are tools (names don't come to mind since I don't
use them, but they're easy to find) which *can* do that
extract to temporary directory thing rather than the InnoSetup
type of installer, but they're relatively rarely used I think.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Online Programming Contest

2005-02-24 Thread Varun
Hi,
It is open for anyone across the world. All times are local ( GMT
+5:30). The contest will be on Feb 27 (this sunday) and i will ensure
that the times are clearly specified.
-Varun

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


Re: Shift Confusion

2005-02-24 Thread Kamilche
 Quite. Although you can sort of see how one might naively arrive at
this
 conclusion: one 7-bit char takes 0...127, which when you put it into
an
 8-bit byte leaves 128...255 unused for a second char

 James

Yep, that's what I was doing. Guess I was too tired to program usefully
last night. 

Thanks for clearing that up, guys!

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


Re: Best IDe

2005-02-24 Thread Jaime Wyant
I demo'd wing ide and have to say it's the best commercial offering. 
The only other one I'm aware of is Komodo and it really can't touch
Wing.

But for me, wingide was slugish.  I have a 1/2 gig of memory and a
pretty hefty CPU - i think its a 1.6 Pentium M [it's a company issued
laptop -- so im not sure of the specs].  I found that as  wing tried
to autocomplete identifiers in large name spaces that it would take a
second or so.  This was really painful when working with wxPython.

What wing does have going for it is a REALLY good auto-completion
system.  Yeah it's slow, but its good.  You wing hints as to what
objects are by using isinstance().  For example, the code below tells
wing that frame is a wx.Frame -

# make_frame returns a wx.Frame
frame = make_frame()

isinstance(frame, wx.Frame)

Once wing has a hint, it'll autocomplete the methods / properties for
you.  But again, it is slow.

As far as free software goes, I really like stani's python editor.  It
seems to *watch* methods that you call on an object and autocomplete
based on that.  For example suppose it sees this code:

# make another wx.Frame
frame = make_frame()
frame.method1()
frame.method2()

...

# Below, stani will autocomplete showing you method1 and method 2.
# No they aren't valid wx.Frame methods!
frame.

HTH,
jw

On 24 Feb 2005 17:31:31 -0800, Harlin Seritt [EMAIL PROTECTED] wrote:
 IDLE, PytonWin and SPE are all free and offer all of the important
 features you'll see even in commercial IDE's.
 
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Flushing print()

2005-02-24 Thread Daniel Yoo
gf gf [EMAIL PROTECTED] wrote:
: Is there any way to make Python's print() flush
: automatically, similar to...mmm...that other
: language's $|=1 ?


Hello gf gf,

Yes; you can use the '-u' command line option to Python, which will
turn off stdout/stderr buffering.


: If not, how can I flush it manually?  sys.stdout.flush() didn't
: seem to work.

H, that's odd.  sys.stdout.flush() should do it.  How are you
testing that stdout isn't flushing as you expect?


Best of wishes to you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Default value for Listbox (Tkinter)

2005-02-24 Thread Harlin Seritt
Whenever I set up something similar:

vals = ['1', '2','3']
for v in vals:
   listbox.inset(END, v)

I notice that when this listbox is displayed, there is never a default
value. How can I make sure that one of the indices is selected by
default?

Thanks,

Harlin

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


Re: web status display for long running program

2005-02-24 Thread John Lenton
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
Brian Roberts wrote:
| I have a command line Python program that sometimes takes a bit
| (several minutes) to run.  I want to provide an optional method for an
| impatient user (me!) to check the status of the program.  The type and
| amount of status information doesn't fit nicely into a --verbose or
| logger -- either too little or too much information at different
| points.
dd and pppd (and probably others) solve this problem by registering
a signal handler that either toggles debug or prints status
information to stderr.
- --
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
Work consists of whatever a body is obliged to do.
Play consists of whatever a body is not obliged to do.
-- Mark Twain
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.0 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
iD8DBQFCHpMZcxEeCh6qRm8RAg11AKCek0hV6QCHw6fm3TM3KAJIXPb1RQCg4qhy
HMr5y+w7fxESkJ2vQ0GEmm0=
=c4bs
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >