Re: extreme newbie

2005-06-18 Thread Peter Hansen
cpunerd4 wrote:
> even so,
> crackers have a harder time getting into compiled programs rather than
> intepreted languages. I know hiding the code won't stop all crackers
> but it will stop some of the casual theifs won't it? It's not so much
> that they could steal code, it's that they could alter it and release
> it somewere else and make their own money off it.

Roughly speaking, if your code is so valuable, there's very little you 
can do to stop if from being used in this way, except for keeping it 
inside a secured "network appliance" which prevents all access (though 
even then the box itself can be stolen, so you have to allow access only 
through the internet in that case).

Furthermore, protecting you from someone else making money off a copy of 
your program is basically what licenses are for, and if you have noticed 
they don't protect even Microsoft (see, for example, entire governments 
like the Indonesian government, which has mass-pirated Microsoft 
software for a long time).

On the other hand, while a license isn't a guarantee of much, it does 
make it easier to go after violators in a court and sue them for 
damages.  And if you think your software is really worth the efforts you 
are envisioning to protect it, you should be prepared to go after people 
in court when they violate your license, not trying to prevent them from 
copying it in the first place (which is basically impossible, except see 
my first point again ;-).

My main suggestion to you is this.  Many people with several decades 
more experience than you used to feel exactly as you do (I did!), and 
have now, after years of developing and selling commercial software, 
changed their view of the whole issue drastically.  Learn from others' 
mistakes and don't waste your time worrying about this "stealing code" 
thing... put your efforts into developing really useful, valuable 
software, and the world will beat a path to your door to give you money 
(see Google, for example), and while a few people might be trying to 
profit from your efforts without your permission, you'll either be in a 
good position to ignore them or sue them, as you will

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


Re: Unbound names in __del__

2005-06-18 Thread Peter Hansen
Torsten Bronger wrote:
> Peter Hansen <[EMAIL PROTECTED]> writes:
>>What's your use case for del?
> 
> Every instance represents a "session" to a measurement instrument.
> After the instance is deleted, the session should be closed to free
> resources.

You mean like GPIB devices?  We've written a lot of software that talks 
to instruments, as well as pumps, motors, and sensors of all kinds.  I 
haven't even needed to "free resources", other than by closing a serial 
port, for example.  Such simple operations don't require the use of 
__del__ and can easily be done with simple .close() type calls as the 
application shuts itself down or finishes a test sequence or other 
operation.

Use of __del__ is, in my opinion, a bit of a crutch (meaning it seems to 
make life easier, but then you start relying on it and find it hard to 
do without).  Given that it isn't really reliable in non-trivial 
situations, I'd recommend pretending __del__ does not exist and 
restructuring your system to close these sessions explicitly, under your 
direct control, at the appropriate point.  This has worked very well for 
us so far.

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


Re: thread.start_new_thread question

2005-06-18 Thread Peter Hansen
Konstantin Veretennicov wrote:
> Thank you, but that doesn't answer my question. I was asking if there
> is a reason that "args" is not optional.

At the risk of increasing your frustration, I'm going avoid answering 
your question as well and simply point out that if you use the 
"threading" module, as is recommended, you won't have to deal with this 
issue at all, and your code will generally be simpler.

(To answer your real question I'd have to check the docs for "thread" 
and, since I _never_ use that module in spite of heavy use of threading, 
I can't help you more... sorry.)

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


Re: How should threads be terminated? (related to 'Help with thread related tracebacks')

2005-06-18 Thread Peter Hansen
Maxwell Hammer wrote:
> On Thu, 16 Jun 2005 16:20:23 -0400, Peter Hansen wrote:
>>If the question was well formulated, and it's been more than a couple of 
>>days, you should consider reposting.  It's very unusual for a post with 
>>such a subject (if it was a clear question) to get _no_ feedback around 
>>here.
> 
> Fair enough. The question is not expressed clearly for others. Do you have
> any suggestions as to how to describe the problem clearer?

I hope you didn't get the impression I was criticizing.  I don't recall 
your post at all, and definitely wasn't suggesting that it was unclear, 
merely asking you to verify that it was and, if not, rewrite it upon 
reposting.

As for suggestions to make it clearer: I can't make any without digging 
back for your previous posting.  I generally don't take the time to do 
that since older messages are often gone from my server very quickly, 
and I don't like spending time digging around on Google Groups to find 
it.  Sorry, it's just one of my approaches to conserving my own time, 
selfishly.

> I can think of no other way but to say I have an app that when I terminate
> it, completes ok, However the last thing that happens before the shell
> prompt returns is that there is a traceback *within* python.
> (The actual post goes into more details of course.)

This sounds very much like the problem where, during the interpreter 
shutdown, all globals in all modules are rebound to None, but if daemon 
threads are still running they will quickly crash as a result and raise 
exceptions, usually referring to AttributeErrors where "None" doesn't 
have an attribute of a particular kind, usually the name of a method.

If I'd seen your post, I would probably have responded with as much at 
the time.  If you do a Google Groups search for some of those keywords 
and my name, you'll certainly find a half dozen other threads where 
someone else asked a similar question, even if I missed your post.

> I just took a guess that it is *thread* related from the output of the
> traceback. I'm still learning python, so how could one pose the problem
> *clearer*? 
> 
> And thanks for the feedback regarding threads, by the way.

No problem.  And if this post didn't help, please do repost the whole 
original question so I can see it again, and those who read the group 
via the mailing list will get a fresh email, etc...

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


Re: Shortcut to initialize variables

2005-06-18 Thread Peter Hansen
Andrew wrote:
> I'm writing a program that will take substitution and transposition
> cipher texts and spit out plain text with no human input. So I suppose
> I'll have dictionaries of digraphs and trigraphs too; for frequency
> analysis. 

 > Do you think this is to heavy of a project to learn the language?

Not at all, provided you're somewhat expert in the domain already, and 
are just using it as a means to help learn Python.

If you are learning both Python and how to break ciphers at the same 
time, I'd personally call it a "little" heavy... ;-)

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


Re: extreme newbie

2005-06-18 Thread cpunerd4
I see your point, although I don't think there is much a 14 year old
can do to sue someone. . . I'm sure my code won't be that valuable
untill I'm older though. Thanks

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


Re: case/switch statement?

2005-06-18 Thread Peter Hansen
D H wrote:
> Peter Hansen wrote:
[some stuff Doug didn't like]

> I don't think you could have misread my simple suggestion to you any 
> more completely than you did.

Sorry, I'll try harder next time.

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


Re: regarding popen function

2005-06-18 Thread Peter Hansen
praba kar wrote:
>The following way of popen function usage is
> wrong or not kindly give me answer regarding this
> 
> time = os.popen("echo %s | tai64nlocal" %
> line[2]).read()

Did you try it?  Just open the Python interactive interpreter and see 
what happens:

Python 2.3.4 (#1, Feb  2 2005, 12:11:53)
[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
 >>> import os
 >>> line = ['', '', '@400042b40a8716ebce34']
 >>> time = os.popen('echo %s | tai64nlocal' % line[2]).read()
 >>> time
'2005-06-18 07:50:21.384552500\n'

Or were you just asking if it was an appropriate way of using 
os.popen()?  If that's what you were asking, it would have been much 
clearer not to include the command itself, since clearly it just 
confuses people about what you are asking.

Yes, it's an appropriate way to use popen(), and it does seem to work if 
you have tai64nlocal in your path.

(Michael, tai64nlocal is a program that converts a special "packed" 
timestamp to human-readable form.  These timestamps are created, as I 
recall, by the multilog program that the developer of Qmail created.)

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


Re: What is different with Python ?

2005-06-18 Thread Peter Hansen
D H wrote:
> Peter Hansen wrote:
>> With respect to the author, and an understanding that there is 
>> probably much that didn't go into his self-description (add 
>> "about.htm" to the above URL), it sounds as though he knows primarily, 
>> perhaps solely, C and C++, and has done relatively little serious 
>> development since he seems to have spent most of his time either 
>> teaching or writing (words, not source code).
>>
>> Does he even *know* any real high level languages such as Python?
> 
> So you say he "has done relatively little serious development" and that 
> he may not even know about Python.  I didn't see any evidence from those 
> pages to draw either conclusion.  In fact the 4th paragraph quite 
> contradicts them both.

Clearly this is a matter of opinion.  Now that you've expressed yours, 
did you have a point to make besides that you like to contradict my 
posts?  Maybe you'd like to take the opportunity to mention Boo?

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


Re: ANN: Concurrence 0.0.5.2 Alpha

2005-06-18 Thread Cockle Cowrie
On 6/17/05, Daniel Bickett <[EMAIL PROTECTED]> wrote:
> Concurrence is a networked file editing program that
enables multiple
> people to modify a document simultaneously. It is
written entirely in
> python, and uses the wxPython library for the GUI
and the Twisted
> library for networking.
> 
> This marks the release of Concurrence 0.0.5.2 Alpha,
and it can be
> found at the following link:
> 
> http://sourceforge.net/projects/concurrence/
> 
> It has been in development for just under three
weeks now, and for
> it's age it has quite a large feature set,
including:
> 
> * All modifications that occur in every client are
sent to the server
> (then to the other clients) real time and on a
first-come, first-serve
> basis
> * The lines on which the carets of the other users
in a given file
> rest are highlighted
> * A chat feature is included in each document window
to eliminate the
> necessity of a third party messenger client, while
improving the
> coordination of document editing
> * All of the features expected of one's day-to-day
text editor have
> been implemented
> * Python files are automatically detected and the
syntax is
> highlighted (in the near future this feature may be
toggled at will)
> 
> The project can be discussed on the #concurrence
channel at
> irc.freenode.net, or on the mailing list
> [EMAIL PROTECTED]
> --
> Daniel Bickett
> dbickett at gmail.com
> http://heureusement.org/
> 



__ 
Yahoo! Mail 
Stay connected, organized, and protected. Take the tour: 
http://tour.mail.yahoo.com/mailtour.html 

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


Re: pysqlite - Checking the existance of a table

2005-06-18 Thread Peter Hansen
Gerhard Häring wrote:
> Or you can query the sqlite_master table (don't know any specification 
> off-hand, but it contains the schema information).

Item #9 in the FAQ (http://www.sqlite.org/faq.html#q9) shows it as:

CREATE TABLE sqlite_master (
   type TEXT,
   name TEXT,
   tbl_name TEXT,
   rootpage INTEGER,
   sql TEXT
);


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


Re: Unbound names in __del__

2005-06-18 Thread Torsten Bronger
Hallöchen!

Peter Hansen <[EMAIL PROTECTED]> writes:

> Torsten Bronger wrote:
>
>> Peter Hansen <[EMAIL PROTECTED]> writes:
>>
>>> What's your use case for del?
>>
>> Every instance represents a "session" to a measurement instrument.
>> After the instance is deleted, the session should be closed to free
>> resources.
>
> You mean like GPIB devices?

Yes.

> We've written a lot of software that talks to instruments, as well
> as pumps, motors, and sensors of all kinds.  I haven't even needed
> to "free resources", other than by closing a serial port, for
> example.  [...]

I've just finished a thin-wrappers implementation of VISA in Python,
see .  It calls functions in a proprietary
VISA DLL/SO.  The next step is to build a simple-to-use OO layer on
top of it.  Therefore, we don't communicate with the device
directly, but via sessions (=handles) within the DLL.

These sessions should be freed when the object instance representing
the device is destroyed by Python.  Using the __del__ method is the
natural choice for this in my opinion.

> [...] I'd recommend pretending __del__ does not exist and
> restructuring your system to close these sessions explicitly,
> under your direct control, at the appropriate point.  This has
> worked very well for us so far.

I'd find this quite sad because so far it's drop-dead simple to use
the OO layer, and I may even convince our in-house HT Basic fans of
Python:

keithley = GpibInstrument(14)
keithley.write("*IDN?")
print keithley.read()

A keithley.close() would be a wart in my opinion; instead I want to
hide the whole session thing from the programmer.  Besides, I
haven't yet given up the hope that the issues with __del__ can be
tackled.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: extreme newbie

2005-06-18 Thread Peter Hansen
cpunerd4 wrote:
> I see your point, although I don't think there is much a 14 year old
> can do to sue someone. . . I'm sure my code won't be that valuable
> untill I'm older though. Thanks

You're probably wrong on the first count, and whether you're wrong on 
the second is entirely up to you. ;-)

(I recall hearing of at least one programmer who made his first million 
around the age of 14 after having written some brilliant game back in 
the days of Apple IIs and C-64s.  These days I'd be surprised if 14 was 
still the lower limit for millionaire status amongst young programmers.)

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


Re: Unbound names in __del__

2005-06-18 Thread Peter Hansen
Torsten Bronger wrote:
> keithley = GpibInstrument(14)
> keithley.write("*IDN?")
> print keithley.read()
> 
> A keithley.close() would be a wart in my opinion; instead I want to
> hide the whole session thing from the programmer.  Besides, I
> haven't yet given up the hope that the issues with __del__ can be
> tackled.

At least one alternative comes to mind.  Have the GpibInstrument class 
(or its module) register an atexit() method, and have the constructor 
for that class track all instances.  On shutdown, the atexit method goes 
through all instruments that are still open and issues the .close() 
requests, or whatever you do in the __del__ now.

In other words, it would be indistinguishable from __del__ from the 
users' point of view, at the cost of a little extra code to make things 
explicit, instead of relying on the implicit and, unfortunately, 
unreliable nature of __del__.  (Which is probably the real wart in 
Python, unfortunately.)

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


Re: Unbound names in __del__

2005-06-18 Thread Torsten Bronger
Hallöchen!

Peter Hansen <[EMAIL PROTECTED]> writes:

> Torsten Bronger wrote:
>
>> keithley = GpibInstrument(14)
>> keithley.write("*IDN?")
>> print keithley.read()
>>
>> A keithley.close() would be a wart in my opinion; instead I want
>> to hide the whole session thing from the programmer.  Besides, I
>> haven't yet given up the hope that the issues with __del__ can be
>> tackled.
>
> At least one alternative comes to mind.  Have the GpibInstrument
> class (or its module) register an atexit() method, and have the
> constructor for that class track all instances.  On shutdown, the
> atexit method goes through all instruments that are still open and
> issues the .close() requests, or whatever you do in the __del__
> now.

However, this doesn't close sessions while the program is running.
If the programmer has the above code in a function which is called
repeatedly, he may run into trouble.  IIRC my current VISA DLL has
only 256 session slots.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [PyKDE] Static (why?) PyDateTimeAPI and SIP

2005-06-18 Thread Gerard Vermeulen
On Sat, 18 Jun 2005 19:52:20 +0400
"Denis S. Otkidach" <[EMAIL PROTECTED]> wrote:

> I use datetime C API in extension module generated with SIP.  But SIP
> break the code into several .cpp files compiled separately and
> PyDateTimeAPI used by all macros constituting public interface is
> declared static.
> 
> The current solution is to define my own functions in main module as
> workaround:
> 
> %ModuleHeaderCode
> PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day,
>   int hour, int minute, int seconds,
>   int usecs);
> %End
> 
> %ModuleCode
> PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day,
>   int hour, int minute, int seconds,
>   int usecs) {
> return PyDateTime_FromDateAndTime(year, month, day, hour, minute, seconds,
>   usecs);
> }
> // and so on for each macro used
> %End
> 
> %PostInitialisationCode
> PyDateTime_IMPORT;
> %End
> 
> But I wonder why PyDateTimeAPI is declared static, and is the a better
> solution?

To prevent namespace pollution.

Numeric and numarray have a different solution. From Numeric/arrayobject.h:

/* C API address pointer */
#if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY)
extern void **PyArray_API;
#else
#if defined(PY_ARRAY_UNIQUE_SYMBOL)
void **PyArray_API;
#else
static void **PyArray_API;
#endif

which lets you use whatever you like and even rename the C API address pointer.

However, keep in mind that SIP can concatenate all C++ files which breaks
clever #defines that work if SIP generates separate C++ source files.

In fact, I use your method, when wrapping the Numeric and numarray files for
PyQwt.  The only difference is that I put all access to the C-API in handwritten
C++ files to use the conflicting APIs of Numeric and numarray in the same Python
extension.

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


Re: extreme newbie

2005-06-18 Thread Steven D'Aprano
On Sat, 18 Jun 2005 12:05:59 -0400, Peter Hansen wrote:

> Furthermore, protecting you from someone else making money off a copy of 
> your program is basically what licenses are for, and if you have noticed 
> they don't protect even Microsoft (see, for example, entire governments 
> like the Indonesian government, which has mass-pirated Microsoft 
> software for a long time).

Please call it what it is: copyright infringement, not piracy. Piracy
takes place in international waters, and involves one or more of theft,
murder, rape and kidnapping. Making an unauthorized copy of a piece of
software is not piracy, it is an infringement of a government-granted
monopoly.

In any case, there is a powerful argument for wanna-be Microsofts to
turn a blind eye to copyright infringements. It worked for Microsoft and
almost every other successful software company.

The biggest barrier to success for software developers is getting people
to even know your software exists. The second biggest barrier is
encouraging them to try your software. The third is getting them to keep
using your software once they've tried it. Actually collecting money from
them is at the bottom of the list -- you can't expect people to pay you
for using your software if they don't even know you exist.

Apart from the occasional public rant (such as Bill Gates' plea to users
not to make illegal copies of MS BASIC), in the early days Microsoft
didn't go out of their way to chase copyright infringers. If they had, the
users would have simply stopped using the MS software and used something
else. Instead, people grabbed copies of Word or Excel from their friends,
taking market share from WordPerfect, WordStar, Lotus etc. Eventually,
they would need an upgrade, or find it more convenient to buy than to
copy. Every so-called "pirated copy" had (at least) four benefits to
Microsoft: it denied a sale to Microsoft's competitors; it increased
users' familiarity and confidence with Microsoft's products; it built
Microsoft's brand recognition among software purchasers and IT
departments; and it was (usually) a future sale to Microsoft.

It was only as Microsoft approached monopoly status that copyright
infringement began to hurt them more than it gained them. With few if any
competitors, the loss of revenue from unauthorized copies of Word or Excel
or Windows became greater than the benefits.

-- 
Steven.



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


Re: extreme newbie

2005-06-18 Thread cpunerd4
the problem is that i don't even know the language yet. . .

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


Re: What makes an object uncopyable?

2005-06-18 Thread Konstantin Veretennicov
On 17 Jun 2005 15:41:07 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> I am trying to make a copy of a certain Python object using the
> copy.copy() function.  When I try to perform this operation I get an
> error like the following:
> 
> copy.Error: un(shallow)copyable object of type ...
> 
> What factors determine whether an object can be copied?

You are probably trying to copy an instance of a class implemented in
C extension. AFAIK, Python classes have copy support by default, but
extension classes need to implement copy/pickle protocol.

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


Re: OO approach to decision sequence?

2005-06-18 Thread Chinook
On Sat, 18 Jun 2005 09:10:25 -0400, George Sakkis wrote
(in article <[EMAIL PROTECTED]>):

> "Chinook" wrote:
> 
>> I understand what you are saying.  The point I'm messing up my head with
>> though, is when the entity (tree node in my case or variable record content
>> deconstructing in the aspect example I noted) is not an instance of a class
>> already - it is obtained from an external source and only decipherable by 
>> its
>> content.
>> 
>> In practical terms that leaves me with some decision sequence regardless and
>> I was wondering (from what Chris Smith said) how that might be done in OOP.
>> The whole problem may be that I'm reading too much into what Chris said :~)
>> I will dig back through the Tutor archives as you suggested.
> 
> What you are looking for is what is called the 'factory method pattern'
> (http://en.wikipedia.org/wiki/Factory_method_pattern) and it's one of
> the cases where OOP doesn't eliminate the if/elif/elif (or switch in
> C++/Java). That's ok though because, as you noticed, at some point you
> have to take a decision. What's important is the "once and only once"
> principle, that is all the decision logic is encapsulated in a single
> method (or in python in a single function) instead of being replicated
> every time you want to use an existing Node.
> 
> Regards,
> George
> 
> 

George,

Yes, that answers my question of how the issue is approached in OOP - thank 
you.  I'll do some more googling to find examples in Python and then try 
refactoring my little utility.  The effect on my little utility will be a 
verbose abstraction of a specific efficient top-down approach, but the 
intended goal is to learn how to better facilitate extensibility.  

Thanks to all that took the time to wade through my post and especially to  
those that offered their thoughts, 

Lee C


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


Re: Unbound names in __del__

2005-06-18 Thread Dieter Maurer
Peter Hansen <[EMAIL PROTECTED]> writes on Fri, 17 Jun 2005 08:43:26 -0400:
> ...
> And I don't recall the last time I saw a __del__ in third-party code I
> was examining.
> 
> 
> What's your use case for del?

I had to use one a few days ago:

 To call the "unlink" method of a "minidom" object when
 its "container" is destroyed.

 It would have been possible to let the cyclic garbage
 collector find and eliminate the cyclic "minidom" objects.
 But, DOMs may be large and I create lots of them in
 a short time (each in its own container)...


Dieter

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


Re: extreme newbie

2005-06-18 Thread Mrsani
> So true. Am I the only one who wonders this: If Python at runtime runs
> very much like Java and has generally about the same
> speed (or faster)

rofl 


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


Re: Unbound names in __del__

2005-06-18 Thread Peter Hansen
Torsten Bronger wrote:
>>Torsten Bronger wrote:
>>>keithley = GpibInstrument(14)
>>>keithley.write("*IDN?")
>>>print keithley.read()
>>
[on using atexit]
> However, this doesn't close sessions while the program is running.
> If the programmer has the above code in a function which is called
> repeatedly, he may run into trouble.  IIRC my current VISA DLL has
> only 256 session slots.

Hmm... it sounds to me as though the design of this DLL is such that one 
is expected to hold a session open for the duration of the application. 
So instead of creating new GpibInstrument objects as needed, then just 
sort of dropping them, the programmers would have to create the required 
instrument objects at the start of the program and reuse them when needed.

But that's as far as my thoughts take me on this, without working 
directly with you.  I guess you'll have to explore the __del__ approach 
through to its conclusion before you'll be confident it won't work (or 
perhaps you'll find a solution after all!).

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


Re: extreme newbie

2005-06-18 Thread Chinook
On Sat, 18 Jun 2005 14:00:35 -0400, Steven D'Aprano wrote
(in article <[EMAIL PROTECTED]>):

> On Sat, 18 Jun 2005 12:05:59 -0400, Peter Hansen wrote:
> 
>> Furthermore, protecting you from someone else making money off a copy of 
>> your program is basically what licenses are for, and if you have noticed 
>> they don't protect even Microsoft (see, for example, entire governments 
>> like the Indonesian government, which has mass-pirated Microsoft 
>> software for a long time).
> 
> Please call it what it is: copyright infringement, not piracy. Piracy
> takes place in international waters, and involves one or more of theft,
> murder, rape and kidnapping. Making an unauthorized copy of a piece of
> software is not piracy, it is an infringement of a government-granted
> monopoly.
> 
> In any case, there is a powerful argument for wanna-be Microsofts to
> turn a blind eye to copyright infringements. It worked for Microsoft and
> almost every other successful software company.
> 
> The biggest barrier to success for software developers is getting people
> to even know your software exists. The second biggest barrier is
> encouraging them to try your software. The third is getting them to keep
> using your software once they've tried it. Actually collecting money from
> them is at the bottom of the list -- you can't expect people to pay you
> for using your software if they don't even know you exist.
> 
> Apart from the occasional public rant (such as Bill Gates' plea to users
> not to make illegal copies of MS BASIC), in the early days Microsoft
> didn't go out of their way to chase copyright infringers. If they had, the
> users would have simply stopped using the MS software and used something
> else. Instead, people grabbed copies of Word or Excel from their friends,
> taking market share from WordPerfect, WordStar, Lotus etc. Eventually,
> they would need an upgrade, or find it more convenient to buy than to
> copy. Every so-called "pirated copy" had (at least) four benefits to
> Microsoft: it denied a sale to Microsoft's competitors; it increased
> users' familiarity and confidence with Microsoft's products; it built
> Microsoft's brand recognition among software purchasers and IT
> departments; and it was (usually) a future sale to Microsoft.
> 
> It was only as Microsoft approached monopoly status that copyright
> infringement began to hurt them more than it gained them. With few if any
> competitors, the loss of revenue from unauthorized copies of Word or Excel
> or Windows became greater than the benefits.
> 
> 

Steven,

Your weigh-in on semantics is misleading, but your elaboration of the aspect 
is very well put.

As to semantics, piracy is to the originator what freedom fighter is to those 
that perceive themselves as oppressed.  

On the other hand, your elaboration is a very good example of the altered 
consciousness of human nature.  That is, the acceptance of shades of 
complicity divorced from shades of guilt.  Of course, one can see (if they so 
chose) many more obvious examples in business, let alone government and 
religion :~)  

Lee C
 


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


oddness in super()

2005-06-18 Thread Michael P. Soulier
Ok, this works in Python on Windows, but here on Linux, with Python 2.4.1, I'm
getting an error. 

The docs say:

A typical use for calling a cooperative superclass method is:

class C(B):
def meth(self, arg):
super(C, self).meth(arg)

However, when I try this, which works on windows, with ActiveState
ActivePython 2.4.0...

class RemGuiFrame(RemGlade.RemFrame):
"""This class is the top-level frame for the application."""

def __init__(self, *args, **kwds):
"Class constructor."
# Constructor chaining
super(RemGuiFrame, self).__init__(*args, **kwds)

...on linux I get this...

[EMAIL PROTECTED] pysrc]$ ./RemGui.py 
Traceback (most recent call last):
  File "./RemGui.py", line 206, in ?
frame_1 = RemGuiFrame(None, -1, "")
  File "./RemGui.py", line 30, in __init__
super(RemGuiFrame, self).__init__(*args, **kwds)
TypeError: super() argument 1 must be type, not classobj

Why the difference? Is Python portability overrated? Is this a bug?

I'm confused. 

Mike

-- 
Michael P. Soulier <[EMAIL PROTECTED]>
http://www.digitaltorque.ca
http://opag.ca  python -c 'import this'
Jabber: [EMAIL PROTECTED]


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: oddness in super()

2005-06-18 Thread Diez B. Roggisch

Michael P. Soulier wrote:

Why the difference? Is Python portability overrated? Is this a bug?


Certainly a bug - but not in python. The super-method works for 
new-style classes only.


The attached script reproduces your observed behaviour. So kit seems 
that whatever toolkit you use, it uses new-style classes on windows, and 
old-style ones on linux.


Regards,

Diez
class Foo(object):
def __init__(self):
print "I'm Foo"

class Bar:
def __init__(self):
print "I'm Bar"


class SubFoo(Foo):
def __init__(self):
super(SubFoo, self).__init__()



class SubBar(Bar):
def __init__(self):
super(SubBar, self).__init__()



SubFoo()
SubBar()

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

Re: extreme newbie

2005-06-18 Thread Ed Jensen
Grant Edwards <[EMAIL PROTECTED]> wrote:
>> I've guessed that python is purely an interpreted language unless its
>> compiled into another language (ie. it needs python installed in order
>> to run programs). Is this correct?
> 
> It's just like Java.  It's compiled into bytecode and then the
> bytecode is executed on a virtual machine.

Keep in mind that all modern JVMs "just-in-time" compile Java bytecode
to native code.  It looks something like this:

Java source -> Java bytecode -> Java virtual machine -> Native code

So, in the end, users are typically running natively compiled code.

(Warning: This is a simplification, but this description seems
adequate for the OP.)

Java typically outperforms Python by a very wide margin.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extreme newbie

2005-06-18 Thread Ed Jensen
Renato Ramonda <[EMAIL PROTECTED]> wrote:
> The only system (apart from solaris, I guess) that has a JVM by default 
> is OSX, and it's _NOT_ sun's one, but the internally developed one.

Apple licenses Sun's JVM and makes the modifications necessary to run
it on OSX.  I know I'm being a pedant, but I don't want people to
think Apple writes their own JVM from scratch.  Also, Java is
installed on lots of systems by companies like Dell and HP; however,
you usually can't predict which version of the JVM is installed or how
the Java auto update features are configured.

That being said, I think Sun is being foolish by not ensuring Java is
free enough to be included with every Linux distribution.  Talk about
letting a golden opportunity slip through their fingers...

As others have pointed out, Python's non-restrictive licensing allows
it to be installed far and wide, and it's easy to bundle a Python
interpreter with your application, which is great.  These are big
advantages for Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extreme newbie

2005-06-18 Thread John Machin
Dennis Lee Bieber wrote:
> On 18 Jun 2005 07:48:13 -0700, "cpunerd4" <[EMAIL PROTECTED]> declaimed
> the following in comp.lang.python:
> 
> 
>>even so,
>>crackers have a harder time getting into compiled programs rather than
>>intepreted languages. I know hiding the code won't stop all crackers
> 
> 
>   A good debugger in step mode can get into anything... At my
> college, those of us with the skills took less than 30 minutes to unlock
> the system assembler after it had been set to run on higher privileged
> accounts (the OS had numeric "priority" levels in accounts; students ran
> at 20 or 40, the assembler had been set to something like 50 to stop the
> troublemakers).  Copy the executable to local, start under debugger,
> step through until the test for account priority was reached, change
> comparison... Voila, private copy of the assembler.
> 

This unnamed OS didn't allow granting execute access but not read access?

I do agree with your main point however. Once you have read access to 
the software, you can do pretty much what you like.


I recall a piece of software that was paid for on an annual licence fee 
basis, and would stop working after a given date. The update sometimes 
arrived late. Fortunately it was a trivial exercise to find the date 
check in the "expired" executable and circumvent it. Debug in step mode? 
How quaint and tedious! All one had to do was to put a Trojan 
DLL-equivalent in the path; this contained a today()-equivalent function 
that simply called the system debug function. Of course the authors 
could have prevented that by dynamically loading the today()-equivalent 
function directly from the manufacturer-supplied system-central 
DLL-equivalent; my guess is that doing so would have prevented easy 
testing of the "stop working" code on a shared machine where they 
couldn't change the system date without upsetting other users, and it's 
probable they were using a Trojan today()-equivalent gadget to supply 
"old" dates for testing.


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


Re: Threading and serial port access

2005-06-18 Thread willie
Diez wrote:

> Apart from that the approach you use is wasting resources - if you are
> concerned about that (or better style...) use e.g. twisted with the
> serial and parallel support and its so-called select reactor. The idea
> behind that concept is that the OS is responsible for scannig IO-Ports.
> It notifies an application about newly arrived data by the system
> function select - which means that your program sits and waits not
> cosuming any resources until actual data arrives. See the module select
> for an overview, and google for "python twisted serial".

Thanks for the help, the code you previously posted worked, but I can
see it could get very messy if the number of ports increased...

I'm going to look at twisted python.  Thanks again for the pointers,
much appreciated.

Regards

William MacLeod

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


Re: Why is there no instancemethod builtin?

2005-06-18 Thread George Sakkis
"Steven Bethard" wrote:

> John Reese wrote:
> > I now do:
> >
> >   if isinstance(x, list):
> >
> > It is my understanding that this is what people do nowadays.
>
> I wouldn't go that far.  I don't have an isinstance check for lists
> anywhere in my entire codebase.  Why do you think you need to check to
> see if something is of type list?  Why don't you just use it as needed,
> and find out, e.g.:
>
> try:
>  itr = iter(x)
> except TypeError:
>  # do whatever you need to do if it's not iterable
> else:
>  # do whatever you need to do if it *is* iterable

A class of cases I've found necessary to do explicit type checking is
when a different action is taken for different types, but where duck
typing can't distinguish between them. For example, a function that
returns a string representation of an S-expression, represented as a
list of nested lists:

def s_expr(obj):
if isinstance(obj, list):
return "(%s)" % ' '.join(map(s_expr,obj))
else:
return str(obj)

>>> s_expr([1, [2,3], [4,5], "foo"])
>>> '(1 (2 3) (4 5) foo)'

Here duck typing doesn't help because the function should take the if
branch only for lists and not other iterables (e.g. strings).

George

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


struct.(un)pack and ASCIIZ strrings

2005-06-18 Thread Sergey Dorofeev
I can use string.unpack if string in struct uses fixed amount of bytes.
But is there some extension to struct modue, which allows to unpack
zero-terminated string, size of which is unknown?
E.g. such struct: long, long, some bytes (string), zero, short, short,
short.


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


Re: Unbound names in __del__

2005-06-18 Thread Terry Reedy

"Torsten Bronger" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> Torsten Bronger wrote:
>>
>>> keithley = GpibInstrument(14)
>>> keithley.write("*IDN?")
>>> print keithley.read()

>>> A keithley.close() would be a wart in my opinion; instead I want
>>> to hide the whole session thing from the programmer.  Besides, I
>>> haven't yet given up the hope that the issues with __del__ can be
>>> tackled.

> However, this doesn't close sessions while the program is running.
> If the programmer has the above code in a function which is called
> repeatedly, he may run into trouble.  IIRC my current VISA DLL has
> only 256 session slots.

Deleting during a run is a different issue from deleting during program 
shutdown, which is where you started us.  In CPython, 'del keithley' will, 
if keithley is the last reference to the object, dependably delete and 
object, calling __del__ on the way.  For other implementations, deleting 
the last reference makes the object eligible to be deleted 'sometime' (if 
and when garbage collection happens).  So an explicit close is the only 
dependable cross-implementation method that I know of.

Terry J. Reedy



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


Re: Regex for repeated character?

2005-06-18 Thread Terry Hancock
On Saturday 18 June 2005 02:05 am, John Machin wrote:
> Doug Schwarz wrote:
> > In article <[EMAIL PROTECTED]>,
> >  Leif K-Brooks <[EMAIL PROTECTED]> wrote:
> >>How do I make a regular expression which will match the same character
> >>repeated one or more times,
> > How's this?
> > 
> >   >>> [x[0] for x in re.findall(r'((.)\2*)', 'abbccccccbba')]
> >   ['a', 'bb', 'ccc', '', 'ccc', 'bb', 'a']
> 
> I think it's fantastic, but I'd be bound to say that given that it's the 
> same as what I posted almost two days ago :-)

Guess there's only one obvious way to do it, then. ;-)

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Unbound names in __del__

2005-06-18 Thread Torsten Bronger
Hallöchen!

"Terry Reedy" <[EMAIL PROTECTED]> writes:

> "Torsten Bronger" <[EMAIL PROTECTED]> wrote:
>
> [...]
>
>> However, this doesn't close sessions while the program is
>> running.  If the programmer has the above code in a function
>> which is called repeatedly, he may run into trouble.  IIRC my
>> current VISA DLL has only 256 session slots.
>
> Deleting during a run is a different issue from deleting during
> program shutdown, which is where you started us.

Well, I talked about shutdown in the OP because only *then* I had
experienced problems.  Cleaning up is important in every phase of
the program, though.

> [...]  So an explicit close is the only dependable
> cross-implementation method that I know of.

I agree, but I could live with the little danger of a Python
implementation that frees so slowly that the DLL runs out of
handles.  One could add a close() method for emergency use.
However, this __del__ thingy is so damn tempting ...  ;-)

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: struct.(un)pack and ASCIIZ strrings

2005-06-18 Thread Terry Reedy

"Sergey Dorofeev" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I can use string.unpack if string in struct uses fixed amount of bytes.

I presume you mean struct.unpack(format, string).  The string len must be 
known when you call, but need not be fixed across multiple calls with 
different strings.

> But is there some extension to struct modue, which allows to unpack
> zero-terminated string, size of which is unknown?
> E.g. such struct: long, long, some bytes (string), zero, short, 
> short,short.



Size is easy to determine.  Given the above and string s (untested code):
prelen = struct.calcsize('2l')
strlen = s.find('\0', prelen) - prelen
format = '2l %ds h c 3h' % strlen # c swallows null byte

Note that C structs can have only one variable-sized field and only at the 
end.  With that restriction, one could slice and unpack the fixed stuff and 
then directly slice out the end string.  (Again, untested)

format = 2l 3h' # for instance
prelen = struct.calcsize(format)
tup = struct.unpack(format, s[:prelen])
varstr = s[prelen, -1] # -1 chops off null byte

Terry J. Reedy



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


Re: extreme newbie

2005-06-18 Thread Harlin Seritt
?

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


Re: oddness in super()

2005-06-18 Thread John Machin
Michael P. Soulier wrote:
> Ok, this works in Python on Windows, but here on Linux, with Python 2.4.1, I'm
> getting an error. 
> 
> The docs say:
> 
> A typical use for calling a cooperative superclass method is:
> 
> class C(B):
> def meth(self, arg):
> super(C, self).meth(arg)
> 
> However, when I try this, which works on windows, with ActiveState
> ActivePython 2.4.0...
> 
> class RemGuiFrame(RemGlade.RemFrame):
> """This class is the top-level frame for the application."""
> 
> def __init__(self, *args, **kwds):
> "Class constructor."
> # Constructor chaining
> super(RemGuiFrame, self).__init__(*args, **kwds)
> 
> ...on linux I get this...
> 
> [EMAIL PROTECTED] pysrc]$ ./RemGui.py 
> Traceback (most recent call last):
>   File "./RemGui.py", line 206, in ?
> frame_1 = RemGuiFrame(None, -1, "")
>   File "./RemGui.py", line 30, in __init__
> super(RemGuiFrame, self).__init__(*args, **kwds)
> TypeError: super() argument 1 must be type, not classobj
> 
> Why the difference?

You are in the best position to answer that; you have access to the 
source code of the place where the problem occurs (RemGui.py), in both a 
"working" instance and a non-"working" instance, so you can (a) read it 
(b) debug it with a debugger, or insert print statements e.g. print 
repr(RemGuiFrame), repr(RemGlade.RemFrame)

You have already noted two variables, OS Windows/Linux, and Python 
2.4.[01]). Are there any others? Perhaps RemGlade.RemFrame comes from a 
3rd party library and there's a version difference.

> Is Python portability overrated?

No. Please stop baying at the moon, and dig out some evidence.

> Is this a bug? 

Is *what* a bug?

Is "it" a bug in what? Windows? Linux? Python 2.4.0? Python 2.4.1? 3rd 
party code? your code?

=

I've never used "super" before, I'm only vaguely aware what it could be 
useful for, and what a "cooperative superclass method" might be, and I 
don't have access to your source code, nor to Linux ... but let's just 
see what can be accomplished if you drag yourself away from that moonlit 
rock and start digging:

First (1) Ooooh what a helpful error message! What is a "classobj"?

Let's RTFM: Hmmm don't tell X** L** but there's no entry for "classobj" 
in the index. But wait, maybe that's geekspeak for "class object" ...
two or three bounces of the pogo-stick later we find this:

"""
Class Types
Class types, or ``new-style classes,'' are callable. These objects 
normally act as factories for new instances of themselves, but 
variations are possible for class types that override __new__(). The 
arguments of the call are passed to __new__() and, in the typical case, 
to __init__() to initialize the new instance.

Classic Classes
Class objects are described below. When a class object is called, a new 
class instance (also described below) is created and returned. This 
implies a call to the class's __init__() method if it has one. Any 
arguments are passed on to the __init__() method. If there is no 
__init__() method, the class must be called without arguments.
"""

(2) Well fancy that... "type" kinda sorta means "new", "classobj" kinda 
sorta means "old"! Now let's re-read the bit about super in TFM:

"""
super() only works for new-style classes
"""

(3) So let's check out our tentative hypothesis:
"""
class Bold:
 def __init__(self):
 print "Bold"

class Bnew(object):
 def __init__(self):
 print "Bnew"

class Cold(Bold):
 def __init__(self):
 print "Cold", repr(Cold), "derives from", repr(Bold)
 super(Cold, self).__init__()
 print "Cold OK"

class Cnew(Bnew):
 def __init__(self):
 print "Cnew", repr(Cnew), "derives from", repr(Bnew)
 super(Cnew, self).__init__()
 print "Cnew OK"

cnew = Cnew()
cold = Cold()
"""

which when run on Python 2.4.1 on a Windows box produces this result:
"""
Cnew  derives from 
Bnew
Cnew OK
Cold  derives from 
Traceback (most recent call last):
   File "C:\junk\soulier.py", line 22, in ?
 cold = Cold()
   File "C:\junk\soulier.py", line 12, in __init__
 super(Cold, self).__init__()
TypeError: super() argument 1 must be type, not classobj

"""

Funny that, the class repr()s are different; not in a meaningful way, 
but the mere difference indicates the classes are products of different 
manufacturers.

(4) Ooooh! How old is the Linux copy of that 3rd party library?

(5) Looks like the bug is in RemGui.py -- it is calling super() with an 
invalid argument. No apparent Python portability problems.

> 
> I'm confused. 

Confession is good for the soul. However true confession is even better 
for the soul. Please come up with a better description. :-)

===

I hope these self-help hints are useful with your next "confusion".

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


Re: Loop until condition is true

2005-06-18 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 Andrea Griffini <[EMAIL PROTECTED]> wrote:

> On Sat, 18 Jun 2005 13:35:16 -, Grant Edwards <[EMAIL PROTECTED]>
> wrote:
> 
> >AFAICT, the main use for do/while in C is when you want to
> >define a block of code with local variables as a macro:
> 
> When my job was squeezing most out of the CPU (videogame
> industry) I remember that the asm code generated by
> 
>while (sz-- > 0)
>{
>  /* do some stuff */
>}
> 
> was indeed worse than
> 
>do
>{
>  /* do some stuff */
>} while (--sz);
> 
> because of the initial "empty-loop" test (conditional jumps
> were bad, and forward conditional jumps were worse).
> So where at least one iteration was guaranteed the do-while
> loop was a better choice.

Hmm.  I don't know what compiler you were using, but in my experience 
it's fairly typical to compile while( ...) {  ... } as

  j test
body: 
  ...
test: 
  ...
  je body  ;; or whatever your condition is

To turn this into a do {  ... } while( ...), you need only 
remove the initial "j test" instruction.  Even if forward conditional 
jumps are bad for your particular architecture, this method avoids the 
problem neatly.

Personally, I'd be pretty suspicious of the quality of a compiler that 
produced radically different code for these two constructs without some 
damned good reason.

-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: struct.(un)pack and ASCIIZ strrings

2005-06-18 Thread John Machin
Terry Reedy wrote:
> "Sergey Dorofeev" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>I can use string.unpack if string in struct uses fixed amount of bytes.
> 
> 
> I presume you mean struct.unpack(format, string).  The string len must be 
> known when you call, but need not be fixed across multiple calls with 
> different strings.
> 
> 
>>But is there some extension to struct modue, which allows to unpack
>>zero-terminated string, size of which is unknown?
>>E.g. such struct: long, long, some bytes (string), zero, short, 
>>short,short.


> Size is easy to determine.  Given the above and string s (untested code):
> prelen = struct.calcsize('2l')
> strlen = s.find('\0', prelen) - prelen
> format = '2l %ds h c 3h' % strlen # c swallows null byte
shouldn't this be '2l %ds c 3h'??

> 
> Note that C structs can have only one variable-sized field and only at the 
> end.  With that restriction, one could slice and unpack the fixed stuff and 
> then directly slice out the end string.  (Again, untested)
> 
> format = 2l 3h' # for instance
> prelen = struct.calcsize(format)
> tup = struct.unpack(format, s[:prelen])
> varstr = s[prelen, -1] # -1 chops off null byte

Perhaps you meant varstr = s[prelen:-1]

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


Re: Regex for repeated character?

2005-06-18 Thread John Machin
Terry Hancock wrote:
> On Saturday 18 June 2005 02:05 am, John Machin wrote:
> 
>>Doug Schwarz wrote:
>>
>>>In article <[EMAIL PROTECTED]>,
>>> Leif K-Brooks <[EMAIL PROTECTED]> wrote:
>>>
How do I make a regular expression which will match the same character
repeated one or more times,
>>>
>>>How's this?
>>>
>>>  >>> [x[0] for x in re.findall(r'((.)\2*)', 'abbccccccbba')]
>>>  ['a', 'bb', 'ccc', '', 'ccc', 'bb', 'a']
>>
>>I think it's fantastic, but I'd be bound to say that given that it's the 
>>same as what I posted almost two days ago :-)
> 
> 
> Guess there's only one obvious way to do it, then. ;-)
> 

Yep ... but probably a zillion ways in
re.compile(r"perl", re.I).match(other_languages)

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


MONEY, MONEYYYY

2005-06-18 Thread LIDERANÇA!!



Querido Amigo,


Você pode ganhar 50.000 REAIS ou mais nos próximos 90 dias, parece
impossível? Prossiga lendo todos os detalhes (não há nada
escondido)...


Atenção: esta é a tradução feita e adaptada para português. No
final desta
tradução encontrará o original em inglês para eventual uso.


DISCUTIDO NA T.V DOS EUA.


Obrigado pelo seu tempo e interesse. Esta é a carta acerca da qual
muito se
tem falado ultimamente nos noticiários dos EUA. Devido à popularidade
desta
carta na Internet, os principais noticiários da noite dedicaram-lhe
imenso
espaço; recentemente foi-lhe mesmo dedicado um espectáculo inteiro
para a
investigação do programa abaixo descrito, tentando concluir se
realmente se
pode ganhar legalmente dinheiro com este sistema.


O espectáculo investigou se o programa era ou não legal. Provou-se de
uma
vez por todas que não há absolutamente nenhum impedimento legal à
participação no programa.
Isto ajudou a mostrar às pessoas que este é um modo simples, inocente
e
divertido para obter dinheiro extra.


Os resultados deste espectáculo foram verdadeiramente notáveis. O
número de
pessoas participantes no sistema aumentou drasticamente. Considerando
que
todos ganham com o aumento do número de participantes, tornou-se
verdadeiramente excitante a participação no sistema. Você entenderá
o que
queremos dizer quando o experimentar.


EIS A DESCRIÇÃO DO SISTEMA


IMPRIMA ESTE TEXTO PARA REFERÊNCIA FUTURA


A seguinte oportunidade de rendimentos poderá ser muito interessante
para
si.


Se você deseja ganhar mais de 50.000 contos em menos de 90 dias! Por
favor
leia o programa
incluído... E NO FINAL... LEIA-O NOVAMENTE!


ESTA É UMA LEGÍTIMA E LEGAL OPORTUNIDADE DE GANHAR MUITO DINHEIRO.


Não lhe exige que entre em contacto com pessoas, fazer qualquer
trabalho
difícil e, melhor que tudo, você nunca tem que deixar a sua casa,
excepto
para se deslocar ao correio.


Se acredita que algum dia ganhará a sorte grande que há muito vem
esperando,
então ELA CHEGOU!
Simplesmente siga as instruções, e os seus sonhos tornar-se-ão
realidade.
Esta ordem multi-nível de
E-mail que comercializa programas, funciona perfeitamente... 100% todas
as
vezes. O E-mail é a ferramenta de vendas do futuro. Beneficie das
vantagens
deste método de publicidade AGORA!!! Quanto mais esperar, mais outras
pessoas estarão negociando. Ganhe o seu pedaço desta acção!!!


O MARKETING de MULTI-NÍVEL (MLM) ganhou, finalmente, respeitabilidade.

Está sendo ensinado na Universidade de Harvard, e em Stanford. O Wall
Street
Journal declarou mesmo que entre 50% e 65% de todos os bem serão
vendidos
por métodos de serviços multi-nível já no final deste ano.


Esta é uma indústria de biliões de dólares e dos 500.000
milionários nos
E.U.A., 20% (100.000) fez a sua fortuna nos últimos anos usando
sistemas
MLM.


Além disso, estatísticas mostram que 45 pessoas se tornam
milionários todos
os dias usando Marketing de multi-nível.


Durante o último verão Donald Trump participou no espectáculo de
David
Letterman. Dave perguntou-lhe o que faria se perdesse a sua imensa
fortuna e
tivesse de recomeçar de novo do nada. Sem vacilar, Trump disse que
criaria
uma empresa que comercializasse em MLM.


A audiência começou a vaiá-lo. Ele olhou a audiência e respondeu -
"É por
isso que eu estou aqui sentando e vocês estão aí do lado de lá"!


Com uma cadeia de marketing você tem duas fontes de renda. Comissões
directas e comissões de vendas através das pessoas que você inicia
no
negócio.


A renda residual é o segredo do sistema. Significa que investindo
apenas
algum tempo e pouquíssimo dinheiro uma única vez irá cobrando
novamente e
novamente e novamente.
A comercialização em rede, também significa ser pago pelo trabalho
de
outros.


UMA NOTA PESSOAL DO CRIADOR DESTE PROGRAMA:


Quando ler o relatório e os programa inclusos, você concluirá que
tais
programas, legais, não poderiam ter sido  criados por um amador.


Deixe-me falar-lhe um pouco de mim. Eu tive um negócio lucrativo
durante 10
anos. Então em 1979 o negócio entrou em queda. Contudo continuava
fazendo o
mesmo que anteriormente resultara perfeitamente, agora, porém,
simplesmente
já não funcionava.
Finalmente compreendi. Não era eu, era a economia que não evoluia
desde
1945. Não será necessário contar-lhe o que aconteceu, por exemplo,
à taxa de
desemprego... provavelmente você saberá dessa terrivel experiência
em
primeira mão. O maior período de sempre de fracassos e bancarrotas.


A classe média arriscava-se a desaparecer. Os que souberam como
sobreviver
investiram sabiamente e moveram-se para cima. Os que o não fizeram
incluindo
os que nunca tiveram qualquer coisa para economizar ou investir,
passaram
para baixo ao grau de pobres. Dando sentido à frase "O RICO TORNA-SE
MAIS
RICO E O POBRE  AINDA MAIS POBRE". Os métodos tradicionais de ganhar
dinheiro já não permitiam mover para cima e ficar rico, a inflacção
além
isso, tratou de que tal não acontecesse.


Você acaba de receber a informação que lhe pode da

Is there something similar to ?: operator (C/C++) in Python?

2005-06-18 Thread Bo Peng
Hi,

I need to pass a bunch of parameters conditionally. In C/C++, I can do

func(cond1?a:b,cond2?c:d,.)

In Python, I am using temporary variables like

if cond1:
   para1 = a
else:
   para1 = b

# 
# a bunch of such if/else

func(para1, para2,...)

Is there an easier way to do this in Python?

BTW, I do not want to use the following since all of a,b,c,d etc will be 
evaluated.

def condValue(cond, val1,val2):
   if cond:
 return val1
   else:
 return val2

func(condValue(cond1,a,b), condValue(cond2,c,d),...)

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


Re: Loop until condition is true

2005-06-18 Thread Joseph Garvin
Peter Otten wrote:

>I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of "for
>(" in the Python 2.4 source, so using these rough estimates do-while still
>qualifies as "rarely used".
>
>Peter
>
>  
>
That's 136 times you'd have to use an ugly hack instead. I definitely 
wouldn't mind an until or do/while.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-18 Thread Peter Hansen
Bo Peng wrote:
> I need to pass a bunch of parameters conditionally. In C/C++, I can do
> func(cond1?a:b,cond2?c:d,.)
> 
> Is there an easier way to do this in Python?

Please read the FAQ to learn the answer and much other useful 
information.  In this case, the specific entry follows, but you'd do 
well to read all the entries:

http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-18 Thread Hsuan-Yeh Chang
Bo Peng wrote:

> Hi,
> 
> I need to pass a bunch of parameters conditionally. In C/C++, I can do
> 
> func(cond1?a:b,cond2?c:d,.)
> 
> In Python, I am using temporary variables like
> 
> if cond1:
>para1 = a
> else:
>para1 = b
> 
> # 
> # a bunch of such if/else
> 
> func(para1, para2,...)
> 
> Is there an easier way to do this in Python?
> 
> BTW, I do not want to use the following since all of a,b,c,d etc will be
> evaluated.
> 
> def condValue(cond, val1,val2):
>if cond:
>  return val1
>else:
>  return val2
> 
> func(condValue(cond1,a,b), condValue(cond2,c,d),...)
> 
> Thanks.
> Bo

take a look at how to use "lambda" in python.

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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-18 Thread Roy Smith
Bo Peng <[EMAIL PROTECTED]> wrote:
> I need to pass a bunch of parameters conditionally. In C/C++, I can do
> 
> func(cond1?a:b,cond2?c:d,.)

Python does not have a ternary operator analogous to C's :?.  There are 
some ugly hacks you can play with the logical operators to emulate :?, but 
in my opinion, the cure is worse than the disease.

> In Python, I am using temporary variables like
> 
> if cond1:
>para1 = a
> else:
>para1 = b
> 
> # 
> # a bunch of such if/else
> 
> func(para1, para2,...)

Yeah, that's how I would do it.  How many of these things do you have?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extreme newbie

2005-06-18 Thread Kent Johnson
Harlin Seritt wrote:
> Am I the only one who wonders this: If Python at runtime runs
> very much like Java and has generally about the same speed (or faster),
> then why in the world isn't Java becoming more archaic and being
> steadily replaced by Python? I ask this not as a rhetorical question,
> but --really-- how come developers are still stuck on Java when Python
> seems to be a far better language? In context, Python is not a low
> level compiled language like C/C++ is but an interpreted one just like
> Java.

Sigh. You're not the only one who wonders this. I have been trying to get my 
co-workers (in a mostly Java shop) interested in Python & Jython for 2-3 years 
with no success. What I see is that
- most of them have little or no time to learn anything new that is not 
directly required to get their job done.
- most of them have zero interest in evaluating new tools and trying to pick 
the best; they just use what is popular.

"I don't have time to sharpen my saw, I'm too busy cutting down this tree!"

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


Re: extreme newbie

2005-06-18 Thread Steven D'Aprano
On Sat, 18 Jun 2005 15:43:24 -0400, Chinook wrote:

> Steven,
> 
> Your weigh-in on semantics is misleading, 

How is it misleading? 

> but your elaboration of the aspect is very well put.
> 
> As to semantics, piracy is to the originator what freedom fighter is to those 
> that perceive themselves as oppressed.  

Very little modern piracy is politically motivated, unlike the glory days
when terrorist nations like Great Britain and Spain supported "privateers"
to attach each other's ships and raid other nations. These days modern
pirates are generally petty criminals in small boats with crews of less
than a dozen people.

http://www.oceannavigator.com/article.php?a=5418
http://www.noonsite.com/Members/webmaster/R2002-06-10-2
http://www.icc-ccs.org/prc/piracyreport.php

> On the other hand, your elaboration is a very good example of the altered 
> consciousness of human nature.  That is, the acceptance of shades of 
> complicity divorced from shades of guilt.  Of course, one can see (if they so 
> chose) many more obvious examples in business, let alone government and 
> religion :~)  

I don't understand your point.

But for the record, I never excused copyright infringement. I simply
pointed out that for organisations who are not monopolies in their
business niche, they gain more benefit from turning a blind eye to most
copyright infringement than they lose.

Or, to put it another way, those developers who face competition in their
market niche and put up barriers to casual copying (eg anti-copying
technology, dongles, serial numbers, licence enforcement, etc) almost
always lose out against competitors who turn a blind eye to that copying.

Copyright infringement may be illegal. It may even be immoral. But for
developers who face competition, ignoring it may be the best strategy.

That's not an issue of human consciousness, altered or not. It is an
economic issue.



-- 
Steven.


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


Re: extreme newbie

2005-06-18 Thread Brian
Hi Cpunerd4,

For beginners, I would strongly recommend checking out 
http://www.GreenTeaPress.com -- they publish a FREE, online book that is 
used in Highschools and other educational facilities to teach Python 
programming.  Excellent -- a must have for those who wish to learn about 
the language.

Brian
---

cpunerd4 wrote:
> Hello programmers,
>   I stumbled onto the python language by chance and it looks like a
> great language. Although from what I've read so far (which isn't much)
> I've guessed that python is purely an interpreted language unless its
> compiled into another language (ie. it needs python installed in order
> to run programs). Is this correct? If it is, I guess my plan of action
> would be to use python embeded in java applets.
>  Another question I have: Does any one know any really good, really
> easy to understand python books? I would prefer one that is avalible
> online for free, but I would also like to know my choices in print.
> Thanks in advance for any advice,
> cpunerd4
> 
> P.S. I'm 14 and I know HTML, PHP, and I know about many others!
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-18 Thread Bo Peng
>>In Python, I am using temporary variables like
>>
>>if cond1:
>>   para1 = a
>>else:
>>   para1 = b
>>
>># 
>># a bunch of such if/else
>>
>>func(para1, para2,...)
> 
> 
> Yeah, that's how I would do it.  How many of these things do you have?

I have around 10 of them. Using these if/else, it will take 50 lines for 
a function call. It also bothers me to have 10 variables left in the 
namespace, in addition to finding 10 meaningful names.

The FAQ provides two solutions, neither of them are elegant. I guess I 
will use if/else for reasability purpose.

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


SciPy gui_thread Problem

2005-06-18 Thread Hsuan-Yeh Chang
Dear SciPy users,

Can anyone tell me the reason for following error messages:

>>> import gui_thread
>>> gui_thread.start()
Traceback (most recent call last):
  File "/usr/lib/python2.4/site-packages/scipy_base/pexec.py", line 56, in
run
exec (code, frame.f_globals,frame.f_locals)
  File "", line 1, in ?
ImportError: /usr/lib/wxPython/lib/libwx_gtk2u_ogl-2.5.so.3: undefined
symbol: _ZNK6wxExpr3NthEi


Thanks!!

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


Re: Loop until condition is true

2005-06-18 Thread Ron Adam
Joseph Garvin wrote:
> Peter Otten wrote:
> 
>> I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of 
>> "for
>> (" in the Python 2.4 source, so using these rough estimates do-while 
>> still
>> qualifies as "rarely used".
>>
>> Peter
>>
>>  
>>
> That's 136 times you'd have to use an ugly hack instead. I definitely 
> wouldn't mind an until or do/while.

I would happy with just having while: without a 1 or True to indicate a 
continuous loop.  Having a if-break at the end doesn't bother me at all.

while:
   
   if : break

Being able to move the break point to where it's needed or have more 
than one is a feature and not a problem. IMHO of course.

It also has the benefit that you have the option to do an extra bit of 
cleanup between the if and the break if you need to.  The until or 
do-while doesn't give you that option.

I suppose if an until : , could be made to be more 
efficient and faster than an if : ; break,  then I'd 
be for that.

   while:
  
  until [: suite]  # optional suite or block
  

But I doubt it would be significantly faster than an if statement with a 
break. So the only benefit I see is you don't have to use the break 
keyword, and the exit conditions will stand out in blocks with a lot of 
if statements in them.

Regards, Ron






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


Re: oddness in super()

2005-06-18 Thread Michael P. Soulier
On 18/06/05 Diez B. Roggisch said:

> Certainly a bug - but not in python. The super-method works for 
> new-style classes only.
> 
> The attached script reproduces your observed behaviour. So kit seems 
> that whatever toolkit you use, it uses new-style classes on windows, and 
> old-style ones on linux.

The code is identical on both. 

I sort-of found the problem. I'm using Ubuntu Linux, and I found both
Python 2.3 and 2.4 installed. /usr/bin/python was 2.4, but things still
weren't working quite right, so I uninstalled all of the 2.3 packages. 

Suddenly everything works. Not entirely sure why, but I guess the 2.4
interpreter was picking up libraries it shouldn't, or something.

Whether a new or old style class depends on wxPython, since my code is
subclassing from wx.Frame. I was concerned since the code is identical
on both platforms, but losing the 2.3 cruft seems to have fixed
something. 

Thanks,
Mike

-- 
Michael P. Soulier <[EMAIL PROTECTED]>
http://www.digitaltorque.ca
http://opag.ca  python -c 'import this'
Jabber: [EMAIL PROTECTED]


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

Extensions on Linux: import without underscore?

2005-06-18 Thread James Carroll
Hi, I'm creating an extension called _bright.so on linux.  I can
import it with import _bright, but how can I import bright and get the
package?

On windows, I've been able to import bright instead of import _bright,
but on Linux it seems to need the underscore.  I'm tempted to create a
bright.py with from _bright import *, but I'm wondering if there's a
more direct way.

Also, I'm using scons to generate my lib, and it insists on prepending
the characters lib to my library name, so if I tell it to generate
_bright.so it gives me lib_bright.so.  Is there a way of turning this
off so I don't have to rename it back to _bright.so?

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


Re: SciPy gui_thread Problem

2005-06-18 Thread Robert Kern
Hsuan-Yeh Chang wrote:
> Dear SciPy users,

If you want to address Scipy users, you should post to the Scipy mailing 
list.

> Can anyone tell me the reason for following error messages:
> 
> 
import gui_thread
gui_thread.start()
> 
> Traceback (most recent call last):
>   File "/usr/lib/python2.4/site-packages/scipy_base/pexec.py", line 56, in
> run
> exec (code, frame.f_globals,frame.f_locals)
>   File "", line 1, in ?
> ImportError: /usr/lib/wxPython/lib/libwx_gtk2u_ogl-2.5.so.3: undefined
> symbol: _ZNK6wxExpr3NthEi

Something has been compiled incorrectly or shared libraries are missing.

In any case, gui_thread probably won't work with wxPython 2.5. 
Development on gui_thread has stopped in favor of ipython's threading 
support.

http://ipython.scipy.org
http://ipython.scipy.org/doc/manual/node5.html#sec:threading-opts

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Extensions on Linux: import without underscore?

2005-06-18 Thread Robert Kern
James Carroll wrote:
> Hi, I'm creating an extension called _bright.so on linux.  I can
> import it with import _bright, but how can I import bright and get the
> package?
> 
> On windows, I've been able to import bright instead of import _bright,

That has to be a bug. You shouldn't rely on that behavior.

> but on Linux it seems to need the underscore.  I'm tempted to create a
> bright.py with from _bright import *, but I'm wondering if there's a
> more direct way.

Call it bright.so .

> Also, I'm using scons to generate my lib, and it insists on prepending
> the characters lib to my library name, so if I tell it to generate
> _bright.so it gives me lib_bright.so.  Is there a way of turning this
> off so I don't have to rename it back to _bright.so?

If at all possible, you should use distutils to build Python extensions.

If you must use Scons, read

   http://www.scons.org/cgi-bin/wiki/PythonExtensions

and use

SharedLibrary(...
   SHLIBPREFIX="",
   ...)

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Extensions on Linux: import without underscore?

2005-06-18 Thread jchiang
Try

SharedLibrary("bright.so", SHLIBPREFIX="", ...)

The prefix option is documented here

http://www.scons.org/doc/HTML/scons-man.html

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


Re: Extensions on Linux: import without underscore?

2005-06-18 Thread James Carroll
Thanks Robert.

> 
> Call it bright.so .
> 

If I rename it bright.so, then I get the error:
  ImportError: dynamic module does not define init function (initbright)

I'm using swig with the module declaration
  %module bright

I've looked at some other source, and it looks like there are some
good reasons to have a bright.py that passes calls on to _bright.

> If at all possible, you should use distutils to build Python extensions.

 Where can I find similar distutils C++ examples?  Can it do most of
what Scons does?

> 
> If you must use Scons, read
> 
>http://www.scons.org/cgi-bin/wiki/PythonExtensions
> 

Very nice, strange that didn't show up for all my googles of scons
python, etc.  I like how it uses distutils to get flags...  I'm
extending wxPython, so I'm using the wxWidgets 
env.ParseConfig('wx-config --cppflags --libs')   Technique... I'll
have to ponder using one or the other or both.  Hmm

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


Re: Extensions on Linux: import without underscore?

2005-06-18 Thread Robert Kern
James Carroll wrote:
> Thanks Robert.
> 
>>Call it bright.so .
> 
> If I rename it bright.so, then I get the error:
>   ImportError: dynamic module does not define init function (initbright)

Sorry, I should have been clearer. Just renaming the file won't help. 
The init function also needs to be appropriately named.

> I'm using swig with the module declaration
>   %module bright
> 
> I've looked at some other source, and it looks like there are some
> good reasons to have a bright.py that passes calls on to _bright.

Reread the SWIG documentation. If it is going to prepend an underscore 
to the extension name, it is usually also generating the appropriate 
bright.py . I suspect that this is why it "worked" on Windows but didn't 
work when you moved to Linux.

>>If at all possible, you should use distutils to build Python extensions.
> 
>  Where can I find similar distutils C++ examples?  Can it do most of
> what Scons does?

Even better, it will handle running SWIG, too. wxPython itself is an 
example, and one that you most certainly should emulate.

>>If you must use Scons, read
>>
>>   http://www.scons.org/cgi-bin/wiki/PythonExtensions
> 
> Very nice, strange that didn't show up for all my googles of scons
> python, etc.  I like how it uses distutils to get flags...  I'm
> extending wxPython, so I'm using the wxWidgets 
> env.ParseConfig('wx-config --cppflags --libs')   Technique... I'll
> have to ponder using one or the other or both.  Hmm

If you're extending wxPython, cannibalize wxPython's build procedure. 
Any other way, there madness lies.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


What platforms have Python Virtual Machines and what version(s) of Python do they support?

2005-06-18 Thread Casey Hawthorne
What platforms have Python Virtual Machines and what version(s) of
Python do they support?
In particular:
Palm OS
PocketPC

What version of Python does Jython support?
Does any machine running a JVM support Jython?
Does it depend on the JVM version and if it's J2ME?

Thank you for your time!

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


Re: pickle alternative

2005-06-18 Thread simonwittber
> I think you should implement it as a C extension and/or write a PEP.
> This has been an unfilled need in Python for a while (SF RFE 467384).

I've submitted a proto PEP to python-dev. It coming up against many of
the same objections to the RFE.

Sw.

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


Re: pickle alternative

2005-06-18 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> > I think you should implement it as a C extension and/or write a PEP.
> > This has been an unfilled need in Python for a while (SF RFE 467384).
> 
> I've submitted a proto PEP to python-dev. It coming up against many of
> the same objections to the RFE.

See also bug# 471893 where jhylton suggests a PEP.  Something really
ought to be done about this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help implementing an idea

2005-06-18 Thread Tim Roberts
[EMAIL PROTECTED] wrote:
>
>Well, I'm a total python n00b, but I was playing around with exception 
>handling 
>yesterday, and was stricken by how incredibly easy it is to use the op system 
>to create nice scripts... I did the following:
>
>import sys
>lines = sys.stdin.readlines()
>lines.sort()
>for stuff in lines:
>print stuff , 

Or sys.stdout.writelines( lines ).

>just to copy stuff from one file to another, and was quite impressed with the 
>results. Now, I was thinking today, I'd really like to create a program that 
>can go to a specific directory and upload all the files in the directory to a 
>specific url for backup purposes, and I have the feeling that the python 
>implementation would be ruthlessly small and efficient, like the 
>aboveanyone who could point me in the right direction as to how to 
>actually 
>do it?

How do you want to do the upload?  FTP?  That's easy.  Check ftplib.py.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overcoming herpetophobia (or what's up w/ Python scopes)?

2005-06-18 Thread Leif K-Brooks
Steven D'Aprano wrote:
> The language is *always* spelt without the "a", and usually all in
> lower-case: perl.

The language is title-cased (Perl), but the standard interpreter is
written in all lowercase (perl). Sort of like the distinction between
Python and CPython.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex for repeated character?

2005-06-18 Thread John Machin
Doug Schwarz wrote:
> In article <[EMAIL PROTECTED]>,
>  Leif K-Brooks <[EMAIL PROTECTED]> wrote:
> 
> 
>>How do I make a regular expression which will match the same character
>>repeated one or more times, instead of matching repetitions of any
>>(possibly non-same) characters like ".+" does? In other words, I want a
>>pattern like this:
>>
>> >>> re.findall(".+", "foo") # not what I want
>> ['foo']
>> >>> re.findall("something", "foo") # what I want
>> ['f', 'oo']
> 
> 
> 
> How's this?
> 
>   >>> [x[0] for x in re.findall(r'((.)\2*)', 'abbccccccbba')]
>   ['a', 'bb', 'ccc', '', 'ccc', 'bb', 'a']
> 

I think it's fantastic, but I'd be bound to say that given that it's the 
same as what I posted almost two days ago :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


functions with unlimeted variable arguments...

2005-06-18 Thread Xah Lee
how can i define a function with variable parameters? For example,

f(a) would return [a]
f(a,b) would return [a,b]
f(a,b,...) would return [a,b,...]

One solution is of course to make the argument as a list. i.e.
f([a,b,...])
but are there other solutions?

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Loop until condition is true

2005-06-18 Thread Peter Otten
Donn Cave wrote:

> If you look at C code, at least in my experience the
> "until" loop is quite rarely used.  (I don't see it once in the source
> to Python 2.4, for example.)

Long time no C? 

'until' in C is actually 

do 
statement
while (expression);

I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of "for
(" in the Python 2.4 source, so using these rough estimates do-while still
qualifies as "rarely used".

Peter

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


Re: What is different with Python ?

2005-06-18 Thread Michele Simionato
Your position reminds me of this:

http://www.pbm.com/~lindahl/real.programmers.html

Michele Simionato

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


Migrating from Windows to OS X

2005-06-18 Thread [EMAIL PROTECTED]
Hello, fellow programmers!

I am sitting in front of a nice new PowerBook portable which has OS
10.4 installed.  The Python.org web site says that Apple has shipped OS
10.4 with Python 2.3.5 installed.  How exactly do I access this?  I
have searched through the Applications and Libraries folders.  I found
the site-packages directory, but nothing other than that.

Thanks for your help,
John Ladasky

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


Re: OO approach to decision sequence?

2005-06-18 Thread Jordan Rastrick
I've coded some simple recursive tree data structures using OO before
(unfortunately not in Python though). It's not nessecarily an
ill-suited approach to the task, although it depends on the specific
details of what you're doing. What's the the piece of code from which
your if...elif fragment is taken actually supposed to do?

Without knowing more about your problem, I think the most obvious OO
approach would be to write a seperate (simple) class for each of
node_type_1, node_type_2, etc. Make sure each one provides the same
interface, i.e. defines the same set of methods. Then put the different
decision branches as implementations of a certain method in each class.

class Node_Type_1(object):
def recurse(self):
 # do stuff here

class Node_Type_2(object):
def recurse(self):
 # do other stuff here

only make sure you use more informative names than "Node_Type_1" and
"recurse" :)

Your if elif code then collapses to:

node.recurse()

where the node variables refers to an instance of any one of your
Node_Type classes.

OO isn't magic. You still in the end have to write the code that
implements the decision choices. In this example, its likely the OO
code is actually more verbose, since you have all the class and method
definitions to write as well.

But there are advantages. Adding new cases (new node_types) is simpler
and less error prone - you just write a new node_type class. The code
for the new class, unlike a new elif brach, is kept cleanly and safely
seperate from your existing, correctly working code. If you forget to
provide the new class with the recurse method, you get a runtime error.
But if you forget to add the case to your if..elif statement, you just
end up silently going with your sentinel "else" branch, which may not
be what you really want to do with that node_type. (in fact I'd usually
raise an exception on reaching the else branch in any such extended
if..elif structure, because it's almost always the result of an error
in your program logic)

Essentially, although you may end up writing more code, its also better
organised, since as you wish it avoids your 'conventional lengthy if
struture'.

Its a partciularily useful approach if you have several different
functions that need to branch on node-type in this fashion (e.g. pretty
print the tree, post-order traverse it, run a search over it, etc). For
each such function, you just provide a method on every node_type class.
Again, if you forget to provide the code for a certain node_type, the
error is very easy to detect.

If your problem is simple, the OO approach may be overkill - your
current if..elif code may be the most straightfoward solution. But if
the problem is complicated, or has the potential to grow more
complicated, the advantages of the OO approach may be a worthwhile
trade off. Fortuantely Python is a multi-paradigm language, so the
choice to use or not use OO according to what best suits the design and
the problem is left up to you, the programmer, and is not thrust upon
you by the language.

And you certainly don't want metaclasses or anything else that complex
and deep for something like this.

Chinook wrote:
> OO approach to decision sequence?
> -
>
> In a recent thread (Cause for using objects?), Chris Smith replied with (in
> part):
>
> >If your table of photo data has several types of photos, and you find
> >yourself saying
> >
> >if is_mugshot:
> >#something
> >elif is_freehand:
> >#something
> >else:
> >#something
> >
> >then OOP will help organize your code.
>
> This struck a chord because I'm trying to refactor a top-down approach to an
> OO approach.  The reason I am doing such is to try and get my mind wrapped
> around OO design, not because the particular module will benefit from an OO
> approach (it's a simple top-down recursive tree utility).  In fact it's
> probably ill suited for OO and that is why I chose it.
>
> I've used an OO approach where I built up record (instance) content in a
> variable record file, but here I'm trying to come at it from the opposite
> direction as variable record mapping (deconstructing) would be to such.
>
> Anyway, a tree node can be any of seven types where:
>
>   if node_type_1:
> # recurse
>   elif node_type_2:
> # terminus - do something
>   elif node_type_3:
> # terminus - do something else
>   ...
>   else:
> # terminus - catch all, do yet something else
>   return #to parent
>
> So, where is the magic :~)  Seriously, how might OO help me organize this
> type of problem (alleviate the conventional lengthy if structure)?  I've
> looked at the cookbook, class interface techniques, factory functions and
> metaclasses till my head is swimming. Am I missing a bolt in the machinery
> somewhere, or simply trying to find magic that doesn't exist for a
> straightforward decision sequence?
> 
> Thank you,
> Lee C

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

Re: smtplib and TLS

2005-06-18 Thread Matthias Kluwe
> "Matthias Kluwe" <[EMAIL PROTECTED]> writes:
>> The server accepts and delivers my messages, but the last command
>> raises

>> socket.sslerror: (8, 'EOF occurred in violation of protocol')

>> Did I miss something? Any hint is welcome.

> Looks like the module didn't send an TLS Close Notify message before
> closing the socket.  I don't see anything in the docs about how to
> send one from smtplib or socket, though.

Hmm. I tried

server.sock.realsock.shutdown(2)

before server.quit() with the result of

SMTPServerDisconnected('Server not connected')

being raised. Quite an improvement ...

Matthias

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


Re: functions with unlimeted variable arguments...

2005-06-18 Thread Paul Rubin
"Xah Lee" <[EMAIL PROTECTED]> writes:
> but are there other solutions?
> 
>  Xah

Geez man, haven't you been around long enough to read the manual?

def f(*a): return a
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Migrating from Windows to OS X

2005-06-18 Thread Kalle Anke
On Sat, 18 Jun 2005 09:26:23 +0200, [EMAIL PROTECTED] wrote
(in article <[EMAIL PROTECTED]>):

> I am sitting in front of a nice new PowerBook portable which has OS
> 10.4 installed.  The Python.org web site says that Apple has shipped OS
> 10.4 with Python 2.3.5 installed.  How exactly do I access this?  I
> have searched through the Applications and Libraries folders.  I found
> the site-packages directory, but nothing other than that.

Launch Terminal (can be found in /Application/Utilities/)

type python

that's it

 jem

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


Re: extreme newbie

2005-06-18 Thread Jordan Rastrick
Another thing to keep in mind is that while technically both Python and
Java are converted into intermediate byte-codes, which are then
interpreted, the Java Virtual Machine runs java bytecode significantly
faster. Partly this is because Sun have put a lot of effort into making
Java as fast as possible, in an attempt to lure away
clockcycle-addicted C programmers; and partly its because having your
langugage statically typed makes it easier to do things quickly (for
technical reasons that I don't fully understand ;)) So Java has and
probably always will have an advantage in the execution speed steaks.

That doesnt change the fact that I'd rather code in Python over Java
any day of the wek, though :)

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


Re: functions with unlimeted variable arguments...

2005-06-18 Thread John Machin
Xah Lee wrote:
> how can i define a function with variable parameters? For example,
> 
> f(a) would return [a]
> f(a,b) would return [a,b]
> f(a,b,...) would return [a,b,...]
> 
> One solution is of course to make the argument as a list. i.e.
> f([a,b,...])
> but are there other solutions?
> 
>>> def foo(*args):
... print repr(args)
... return list(args)
...
>>> foo()
()
[]
>>> foo(42)
(42,)
[42]
>>> foo(666, 'hello', 1.234)
(666, 'hello', 1.234)
[666, 'hello', 1.234]
>>>

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


Re: smtplib and TLS

2005-06-18 Thread Paul Rubin
"Matthias Kluwe" <[EMAIL PROTECTED]> writes:
> Hmm. I tried
> 
> server.sock.realsock.shutdown(2)
> before server.quit() with the result of

I don't think that's exactly what you want.  You need to send a
specific TLS message BEFORE shutting down the socket, to tell the
other end that the TLS connection is ending.  That tells the server
that it shouldn't accept a TLS session resumption later.  The close
notify message is required because if you don't send it, an attacker
could truncate one of your TLS messages by cutting your connection.

Basically the socket library's SSL implementation is pretty crude.
You might try http://trevp.net/tlslite for a pure-Python
implementation that's also still missing stuff, but is getting there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python documentation problem

2005-06-18 Thread Xah Lee
Python documentation,
http://python.org/doc/2.4.1/lib/typesfunctions.html

-
 2.3.10.3 Functions

Function objects are created by function definitions. The only
operation on a function object is to call it: func(argument-list).

There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the different
object types.

See the Python Reference Manual for more information.
-

Fuck the python doc wasted my time. Fuck python coders.
Each time i tried to use python doc and got frustrated because it being
grossly incompetent, i'll post a message like this, no more frequent
than once a week. This will go on as long the python community does
nothing to fix it or that i remain coding in python.
For reference, see
 http://xahlee.org/perl-python/re-write_notes.html

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: OO approach to decision sequence?

2005-06-18 Thread Brian van den Broek
Chinook said unto the world upon 18/06/2005 02:17:
> OO approach to decision sequence?
> -
> 
> In a recent thread (Cause for using objects?), Chris Smith replied with (in 
> part):
> 
> 
>>   If your table of photo data has several types of photos, and you find
>>   yourself saying
>>   
>>   if is_mugshot:
>>   #something
>>   elif is_freehand:
>>   #something
>>   else:
>>   #something
>>   
>>   then OOP will help organize your code.
> 
> 
> This struck a chord because I'm trying to refactor a top-down approach to an 
> OO approach.  The reason I am doing such is to try and get my mind wrapped 
> around OO design, not because the particular module will benefit from an OO 
> approach (it's a simple top-down recursive tree utility).  In fact it's 
> probably ill suited for OO and that is why I chose it.  
> 
> I've used an OO approach where I built up record (instance) content in a 
> variable record file, but here I'm trying to come at it from the opposite 
> direction as variable record mapping (deconstructing) would be to such.  
> 
> Anyway, a tree node can be any of seven types where:
> 
>   if node_type_1:
> # recurse
>   elif node_type_2:
> # terminus - do something
>   elif node_type_3:
> # terminus - do something else
>   ...
>   else:
> # terminus - catch all, do yet something else
>   return #to parent
> 
> So, where is the magic :~)  Seriously, how might OO help me organize this 
> type of problem (alleviate the conventional lengthy if structure)?  I've 
> looked at the cookbook, class interface techniques, factory functions and 
> metaclasses till my head is swimming. Am I missing a bolt in the machinery 
> somewhere, or simply trying to find magic that doesn't exist for a 
> straightforward decision sequence?
> 
> Thank you,
> Lee C


Hi Lee,

I'm a hobbyist who came to grok the OO approach in the last 6 months 
or so ago. So, take the comments with that in mind.

A simple toy example with the "if type" test approach:

 >>> class A(object):
... pass
...
 >>> class B(object):
... pass
...
 >>> a = A()
 >>> b = B()
 >>> for item in (a, b):
... if type(item) == A:
... ident = "an A"
... if type(item) == B:
... ident = "a B"
... print "Found %s" %ident
... 
Found an A
Found a B
 >>>


Now, the same sort of behaviour where the "if type" testing has been 
replaced with code more in keeping with the OOP approach:

 >>> class C(object):
... def report(self):
... print "Found a C"
... 
 >>> class D(object):
... def report(self):
... print "Found a D"
... 
 >>> c = C()
 >>> d = D()
 >>> for item in (c, d):
... item.report()
... 
Found a C
Found a D
 >>>


A metaphorical explanation that is a bit handwavy, but that I find useful:

In both approaches, there is a common behaviour you want the various 
types of objects to exhibit. (In a less 'toy' example the behaviour 
would be more complicated.)

In the "if type" style, you are asking each object what kind of object 
it is, and then setting an aspect of the behaviour as a function of 
the answer.

In the more OOP approach, you rely on the fact that each object knows 
what kind of object it is. So, you don't need to ask it, and adjust 
the behaviour accordingly. You just tell it to behave, and, knowing 
what kind of thing it is, it knows how to behave as befits that kind 
of thing.

Two big benefits in the context are that if you need to exhibit the 
same behaviour in multiple places, you don't have multiple "if type" 
chains, and, if you want to add a type, with its own specific 
behaviour, you just add a class, and there is no worry about hunting 
down the "if type" chains to update them.

There was a thread on the tutor list around mid-Feb. which really 
helped me come to understand the idea. Actually, from Dec. to Feb. or 
so, there are several long tutor threads where people gave me much 
useful help coming to see how to employ OOP. Might be worth a trip 
through the archive.

HTH,

Brian vdB


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


Re: Python documentation problem

2005-06-18 Thread Erik Max Francis
Xah Lee wrote:

> Fuck the python doc wasted my time. Fuck python coders.

Use your words!

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   The mind is not a vessel to be filled but a fire to be kindled.
   -- Plutarch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO approach to decision sequence?

2005-06-18 Thread John Machin
Jordan Rastrick wrote:
> I've coded some simple recursive tree data structures using OO before
> (unfortunately not in Python though). It's not nessecarily an
> ill-suited approach to the task, although it depends on the specific
> details of what you're doing. What's the the piece of code from which
> your if...elif fragment is taken actually supposed to do?
> 
> Without knowing more about your problem, I think the most obvious OO
> approach would be to write a seperate (simple) class for each of
> node_type_1, node_type_2, etc. Make sure each one provides the same
> interface, i.e. defines the same set of methods. Then put the different
> decision branches as implementations of a certain method in each class.
> 
> class Node_Type_1(object):
> def recurse(self):
>  # do stuff here
> 

etc etc

and perhaps if you found by the time you got to Node_Type_2 that its 
opensesame() method was identical to the opensesame() method for 
Node_Type_1, you might decide that having separate simple classes could 
be improved on by having a Node class, which you would subclass for each 
Node_Type_n ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Back to the future - python to C++ advice wanted

2005-06-18 Thread Kay Schluehr
D H wrote:

> That's why so many people have switched to Java or C# (or Python and
> other langugages of course).  You might talk to them about using Python,
> since Python and C/C++ fit together very nicely (with tools like BOOST,
> SWIG, Pyrex,...).  But me personally I like to avoid C++ altogether when
> possible, and use Java or C# instead, both of which also can be combined
> with python or python-like languages such as jython, groovy, or boo.

But accessing Java packages from jython does not reduce effecively the
underlying pain. Personally I favour for programming in C++ over Java,
because I feel at least the mind of an evil genius ( C++ template
programming is Turing complete, operator overloading enables objects
having a builtin groove ) where Java is plain mediocrity. In spirit it
is a kind of Anti-Python.

I recommend studying C++ idioms carefully.

http://www1.bell-labs.com/user/cope/Patterns/C++Idioms/EuroPLoP98.html

If Georges starts on greenfields he may have a look at Qt and it's
object library which is not only concerned with widgets.

http://doc.trolltech.com/3.3/

BOOST is more high brow and I guess that it compiles slow because it
uses templates extensively. Template metaprogramming as a compile time
language was a funny discovery. Here is some prove of it's
capabilities:

http://osl.iu.edu/~tveldhui/papers/2003/turing.pdf

Regards,
Kay

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


Re: Python documentation problem

2005-06-18 Thread Xah Lee
i wanted to find out if Python supports eval. e.g.

somecode='3+4'
print eval(somecode) # prints 7

in the 14 hundred pages of python doc, where am i supposed to find this
info?

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Python documentation problem

2005-06-18 Thread Brian van den Broek
Xah Lee said unto the world upon 18/06/2005 03:49:
> Python documentation,
> http://python.org/doc/2.4.1/lib/typesfunctions.html
> 
> -
>  2.3.10.3 Functions
> 
> Function objects are created by function definitions. The only
> operation on a function object is to call it: func(argument-list).
> 
> There are really two flavors of function objects: built-in functions
> and user-defined functions. Both support the same operation (to call
> the function), but the implementation is different, hence the different
> object types.
> 
> See the Python Reference Manual for more information.
> -
> 
> Fuck the python doc wasted my time. Fuck python coders.
> Each time i tried to use python doc and got frustrated because it being
> grossly incompetent, i'll post a message like this, no more frequent
> than once a week. This will go on as long the python community does
> nothing to fix it or that i remain coding in python.
> For reference, see
>  http://xahlee.org/perl-python/re-write_notes.html
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/

I'm sure I will regret this in the morning . . . .

Xah, since the docs are a community effort, you surely can (and have) 
pointed to genuine blemishes in them.

I am however at a loss to understand just what the perceived problem 
is here. 5 short sentences, one defining a term, 1 stipulating the 
interface, two pointing out and clearing up a potential cause of 
confusion, and a reference. All are clear, and score quite well on the 
content:words measure to boot. (Certainly it is clearer and more 
informative than the words either you or I have here added.) What's 
your complaint? Not enough cursing?

Best,

Brian vdB

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

Re: Python documentation problem

2005-06-18 Thread Brian van den Broek
Xah Lee said unto the world upon 18/06/2005 04:11:
> i wanted to find out if Python supports eval. e.g.
> 
> somecode='3+4'
> print eval(somecode) # prints 7
> 
> in the 14 hundred pages of python doc, where am i supposed to find this
> info?
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/
> 


which I got to from 

in less time that in took to type this.

Best,

Brian vdB

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

Re: Python documentation problem

2005-06-18 Thread John Machin
Xah Lee wrote:
> i wanted to find out if Python supports eval. e.g.
> 
> somecode='3+4'
> print eval(somecode) # prints 7
> 
> in the 14 hundred pages of python doc, where am i supposed to find this
> info?
> 

Option 1: As they say in the classics, "Suck it and see".
If you want to find out if something is supported, just type it in:

  >>> somecode = '3+4'
  >>> eval(somecode)
  7
  >>>

Option 2: Use help():

  >>> help(eval)
Help on built-in function eval in module __builtin__:

eval(...)
 eval(source[, globals[, locals]]) -> value

 Evaluate the source in the context of globals and locals.
 The source may be a string representing a Python expression
 or a code object as returned by compile().
 The globals must be a dictionary and locals can be any mappping,
 defaulting to the current globals and locals.
 If only globals is given, locals defaults to it.

Option 3: If you have Windows, it's easy to find, just click on the 
Python documentation icon, then select the index tab, and type in "eval" 
(or whatever).

Option 4: On the Python website, click on the docs link, then choose 
library reference manual, then either go to the built-in functions, or 
go to the index and select "eval" -- this latter method will take you to 
this link:

http://www.python.org/doc/2.4.1/lib/built-in-funcs.html#l2h-23

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


Re: OO approach to decision sequence?

2005-06-18 Thread Chinook
On Sat, 18 Jun 2005 03:52:28 -0400, Brian van den Broek wrote
(in article <[EMAIL PROTECTED]>):

> Chinook said unto the world upon 18/06/2005 02:17:
>> OO approach to decision sequence?
>> -
>> 
>> In a recent thread (Cause for using objects?), Chris Smith replied with (in 
>> part):
>> 
>> 
>>> If your table of photo data has several types of photos, and you find
>>> yourself saying
>>> 
>>> if is_mugshot:
>>> #something
>>> elif is_freehand:
>>> #something
>>> else:
>>> #something
>>> 
>>> then OOP will help organize your code.
>> 
>> 
>> This struck a chord because I'm trying to refactor a top-down approach to 
>> an 
>> OO approach.  The reason I am doing such is to try and get my mind wrapped 
>> around OO design, not because the particular module will benefit from an OO 
>> approach (it's a simple top-down recursive tree utility).  In fact it's 
>> probably ill suited for OO and that is why I chose it.  
>> 
>> I've used an OO approach where I built up record (instance) content in a 
>> variable record file, but here I'm trying to come at it from the opposite 
>> direction as variable record mapping (deconstructing) would be to such.  
>> 
>> Anyway, a tree node can be any of seven types where:
>> 
>> if node_type_1:
>> # recurse
>> elif node_type_2:
>> # terminus - do something
>> elif node_type_3:
>> # terminus - do something else
>> ...
>> else:
>> # terminus - catch all, do yet something else
>> return #to parent
>> 
>> So, where is the magic :~)  Seriously, how might OO help me organize this 
>> type of problem (alleviate the conventional lengthy if structure)?  I've 
>> looked at the cookbook, class interface techniques, factory functions and 
>> metaclasses till my head is swimming. Am I missing a bolt in the machinery 
>> somewhere, or simply trying to find magic that doesn't exist for a 
>> straightforward decision sequence?
>> 
>> Thank you,
>> Lee C
> 
> 
> Hi Lee,
> 
> I'm a hobbyist who came to grok the OO approach in the last 6 months 
> or so ago. So, take the comments with that in mind.
> 
> A simple toy example with the "if type" test approach:
> 
>  >>> class A(object):
> ...   pass
> ...
>  >>> class B(object):
> ...   pass
> ...
>  >>> a = A()
>  >>> b = B()
>  >>> for item in (a, b):
> ...   if type(item) == A:
> ...   ident = "an A"
> ...   if type(item) == B:
> ...   ident = "a B"
> ...   print "Found %s" %ident
> ...   
> Found an A
> Found a B
>  >>>
> 
> 
> Now, the same sort of behaviour where the "if type" testing has been 
> replaced with code more in keeping with the OOP approach:
> 
>  >>> class C(object):
> ...   def report(self):
> ...   print "Found a C"
> ...   
>  >>> class D(object):
> ...   def report(self):
> ...   print "Found a D"
> ...   
>  >>> c = C()
>  >>> d = D()
>  >>> for item in (c, d):
> ...   item.report()
> ...   
> Found a C
> Found a D
>  >>>
> 
> 
> A metaphorical explanation that is a bit handwavy, but that I find useful:
> 
> In both approaches, there is a common behaviour you want the various 
> types of objects to exhibit. (In a less 'toy' example the behaviour 
> would be more complicated.)
> 
> In the "if type" style, you are asking each object what kind of object 
> it is, and then setting an aspect of the behaviour as a function of 
> the answer.
> 
> In the more OOP approach, you rely on the fact that each object knows 
> what kind of object it is. So, you don't need to ask it, and adjust 
> the behaviour accordingly. You just tell it to behave, and, knowing 
> what kind of thing it is, it knows how to behave as befits that kind 
> of thing.
> 
> Two big benefits in the context are that if you need to exhibit the 
> same behaviour in multiple places, you don't have multiple "if type" 
> chains, and, if you want to add a type, with its own specific 
> behaviour, you just add a class, and there is no worry about hunting 
> down the "if type" chains to update them.
> 
> There was a thread on the tutor list around mid-Feb. which really 
> helped me come to understand the idea. Actually, from Dec. to Feb. or 
> so, there are several long tutor threads where people gave me much 
> useful help coming to see how to employ OOP. Might be worth a trip 
> through the archive.
> 
> HTH,
> 
> Brian vdB
> 
> 
> 

Thanks for the reply Brian.

I understand what you are saying.  The point I'm messing up my head with 
though, is when the entity (tree node in my case or variable record content 
deconstructing in the aspect example I noted) is not an instance of a class 
already - it is obtained from an external source and only decipherable by its 
content.  

In practical terms that leaves me with some decision sequence regardless and 
I was wondering (from what Chris Smith said) how that might be done in OOP.  
The whole problem may be that I'm reading too much into what Chris said :~)  
I will dig back through the Tutor archives as you suggested.

Thanks again,
L

Re: Migrating from Windows to OS X

2005-06-18 Thread Chinook
On Sat, 18 Jun 2005 03:26:23 -0400, [EMAIL PROTECTED] wrote
(in article <[EMAIL PROTECTED]>):

> Hello, fellow programmers!
> 
> I am sitting in front of a nice new PowerBook portable which has OS
> 10.4 installed.  The Python.org web site says that Apple has shipped OS
> 10.4 with Python 2.3.5 installed.  How exactly do I access this?  I
> have searched through the Applications and Libraries folders.  I found
> the site-packages directory, but nothing other than that.
> 
> Thanks for your help,
> John Ladasky
> 
> 

You might also want to take a look at:
http://undefined.org/python/#TigerPython24Fix

That is if you want to use Python 2.4.1  

There is also a Python SIG for us Mac elitists :~) 
 http://mail.python.org/mailman/listinfo/pythonmac-sig
 

Lee C


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


Re: regarding popen function

2005-06-18 Thread Michael Hoffman
praba kar wrote:

>The following way of popen function usage is
> wrong or not kindly give me answer regarding this
> 
> time = os.popen("echo %s | tai64nlocal" %
> line[2]).read()

I don't know, I don't know what tai64nlocal is or what's in line[2]. 
What happened when you tried it?

Personally I try to use the subprocess module rather than os.popen.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overcoming herpetophobia (or what's up w/ Python scopes)?

2005-06-18 Thread Steven D'Aprano
On Sat, 18 Jun 2005 04:26:13 +, Dennis Lee Bieber wrote:

> On Sat, 18 Jun 2005 03:02:13 +1000, Steven D'Aprano
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
>> 
>> The language is *always* spelt without the "a", and usually all in
>> lower-case: perl.
>>
>   Given that, at least one well known, book relates the name to
> Practical Extraction (&) Report Language, whether that was a retrofit or
> not -- I'd be tempted to user PERL for the name...

According to Larry Wall, PERL is *officially* wrong and should *never* be
used.


> All lowercase most
> likely reflects the standard habits of Linux/Unix command naming.

And since Larry came from that tradition, you are most likely
correct. And that is why originally the official name of the language was
all lowercase. Things change, and now Perl is officially the name of the
language, and perl officially the name of the implementation of the
language.

Reading the Perl FAQs at www.perl.org is a good place to start.

-- 
Steven.

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


Using swig to use an existing dll/library

2005-06-18 Thread peter . o . mueller
Hi together,

i have a Windows DLL in C that is internally multithreaded and provides
a callback function to signal specific events. As I understood one can
use "normal" C-code with swig. Is it also possible to use existing
DLLs? Does swig can also handel the callback method? If not - is there
another wrapper toolkit that can do that?

Thanks,
Peter

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


Re: Python documentation problem

2005-06-18 Thread Xah Lee
Apparently i tried it before posting
eval '3'
and got misleading errors because i forgot the parenthesis...

This is a easy one to find in the doc...
The unhelpful doc organization and past experiences confounded this
case.

Thanks.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: exceptions considered harmful

2005-06-18 Thread Steven D'Aprano
On Fri, 17 Jun 2005 20:00:39 -0400, Roy Smith wrote:

> "H. S. Lahman" <[EMAIL PROTECTED]> wrote:
>> > Never throw an exception. And if someone throws one at you,
>> > catch it immediately and don't pass it on.
>> 
>> IMO, this is generally fine advice.  Languages provide exception 
>> handlers so that applications have a chance to respond gracefully when 
>> the software is in an unstable state.  IOW, you should never see an 
>> exception unless the software is seriously broken.  A corollary is that 
>> if the software is corrupted, then even processing the exception becomes 
>> high risk.  So one should do as little as possible when processing 
>> exceptions.  (Some languages provide a degree of bullet proofing, but 
>> that just make the exception handling facility too expensive to use for 
>> routine processing.)
> 
> This sounds like a very C++ view of the world.  In Python, for example, 
> exceptions are much more light weight and perfectly routine.


Yes. Furthermore, there is a reason why they are called exceptions and not
errors. Exceptions don't necessarily mean "something has gone wrong". They
can also mean, "something has gone right, but it is an exceptional case". 

For example, Guido recommends using exceptions for handling exceptional
cases for command-line tools. Eg, something like this:

try:
for switch in sys.argv[1:]:
if switch in ("-h", "--help"):
raise HelpException
else:
do_something()
except HelpException:
print __doc__
sys.exit(0)  # because asking for help is not an error
except:
print "Program failed!"
sys.exit(1)  # but an error is an error
do_main_calculation()
sys.exit(0)

Or something like this:

try:
# long slow calculation
do_lots_of_work_here()
if condition():
# we can jump out of the slow calculation and take a short cut
raise QuickException
# and more long slow calculation here
partial_result = do_lots_more_work_here()
except QuickException:
# short and easy calculation
partial_result = do_quick_calculation()
# in either case, we need to do more work here
return do_more_work(partial_result)

Or even roll-back of processing:

try:
process_data()  # can raise RecoverableError or FatalError
except RecoverableError:
roll_back()
except FatalError:
print "A fatal error occurred."
sys.exit(1)

Because Python's handling of try...except is lightweight and fast, this is
an idiom which is very practical to use in many situations where it
wouldn't be practical in other languages.

In conclusion: in Python, it is just not true that "you should never see
an exception unless the software is seriously broken". It is very bad
advice to say that "even processing the exception becomes high risk".

If the exception genuinely is an error, then it may be difficult to
recover, and the best thing you can do is fail gracefully. But that's no
reason to not use exceptions.



-- 
Steven.


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


Re: Python documentation problem

2005-06-18 Thread Tassilo v. Parseval
Also sprach Xah Lee:

> i wanted to find out if Python supports eval. e.g.
>
> somecode='3+4'
> print eval(somecode) # prints 7
>
> in the 14 hundred pages of python doc, where am i supposed to find this
> info?

You are not going to find it in comp.lang.perl.misc.

Tassilo
-- 
use bigint;
$n=71423350343770280161397026330337371139054411854220053437565440;
$m=-8,;;$_=$n&(0xff)<<$m,,$_>>=$m,,print+chr,,while(($m+=8)<=200);
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python documentation problem

2005-06-18 Thread Xah Lee
> what is wrong with python doc
> http://python.org/doc/2.4.1/lib/typesfunctions.html

the problem is that the page essentially says nothing. Nothing that is
relevant to programing, and such nothingness occupies a significant
portion of the python doc. (at least a quarter) It is like reading a
manual to operate a machinery, and in every other paragraph it offers
the (technically-fantastically-correct) explanations of what bolt or
material were used where.

the cause of such nothingness situation is because the brainlessness
approach to doc organization coupled with standard computer industry
geeking moron's need to computer-sciency speak with implementation
infatuation. And in part it came to that really because they are
comparative morons.

for a more sincere, detailed account, please see:
http://xahlee.org/perl-python/re-write_notes.html

Thanks.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: pygtk question

2005-06-18 Thread Christophe Lambin
"RunLevelZero" <[EMAIL PROTECTED]> wrote:

> Hopefully someone can help me out here.  It's probably super simple but
> how do you select multiple items in a treeview?  I have
> gtk.SELECTION_MULTIPLE set but of course that was enough.

It should be enough to do this:

treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)

If it doesn't work, try posting a short example so someone can have a
look.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python documentation problem

2005-06-18 Thread Kalle Anke
On Sat, 18 Jun 2005 11:49:38 +0200, Xah Lee wrote
(in article <[EMAIL PROTECTED]>):

> the problem is that the page essentially says nothing. Nothing that is
> relevant to programing, and such nothingness occupies a significant
> portion of the python doc. (at least a quarter) It is like reading a
> manual to operate a machinery, and in every other paragraph it offers
> the (technically-fantastically-correct) explanations of what bolt or
> material were used where.

I'm new to Python and the information that's in the docs (at least that 
example) was what I was looking for. I read this as the referece manual, not 
a cookbook or a tutorial which clearly requires another style of 
documentation.

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


Re: utf8 and ftplib

2005-06-18 Thread Fredrik Lundh
Richard Lewis wrote:

> OK, I've fiddled around a bit more but I still haven't managed to get it
> to work. I get the fact that its not the FTP operation thats causing the
> problem so it must be either the xml.minidom.parse() function (and
> whatever sort of file I give that) or the way that I write my results to
> output files after I've done my DOM processing. I'll post some more
> detailed code:
>
> def open_file(file_name):
>ftp = ftplib.FTP(self.host)
>ftp.login(self.login, self.passwd)
>
>content_file = file(file_name, 'w+b')
>ftp.retrbinary("RETR " + self.path, content_file.write)
>ftp.quit()
>content_file.close()
>
>## Case 1:
>#self.document = parse(file_name)
>
>## Case 2:
>#self.document = parse(codecs.open(file_name, 'r+b', "utf-8"))
>
># Case 3:
>content_file = codecs.open(file_name, 'r', "utf-8")
>self.document = parse(codecs.EncodedFile(content_file, "utf-8",
>"utf-8"))
>content_file.close()
>
> In Case1 I get the incorrectly encoded characters.

case 1 is the only one where you use the XML parser as it is designed to
be used (on the stream level, XML is defined in terms of encoded text,
not Unicode characters.  the parser will decode things for you)

given that he XML tree returned by the parser contains *decoded* Uni-
code characters (in Unicode string objects), what makes you so sure that
you're getting "incorrectly encoded characters" from the parser?



(I wonder why this is so hard for so many people?  hardly any programmer has
any problem telling the difference between, say, a 32-bit binary floating point
value on disk, a floating point object, and the string representation of a 
float.
but replace the float with a Unicode character, and anglocentric programmers
immediately resort to poking-with-a-stick-in-the-dark programming. I'll figure
it out, some day...) 



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


Re: Python documentation problem

2005-06-18 Thread Steven D'Aprano
On Sat, 18 Jun 2005 12:02:07 +0200, Kalle Anke wrote:

> On Sat, 18 Jun 2005 11:49:38 +0200, Xah Lee wrote
> (in article <[EMAIL PROTECTED]>):
> 
>> the problem is that the page essentially says nothing. Nothing that is
>> relevant to programing, and such nothingness occupies a significant
>> portion of the python doc. (at least a quarter) It is like reading a
>> manual to operate a machinery, and in every other paragraph it offers
>> the (technically-fantastically-correct) explanations of what bolt or
>> material were used where.
> 
> I'm new to Python and the information that's in the docs (at least that 
> example) was what I was looking for. I read this as the referece manual, not 
> a cookbook or a tutorial which clearly requires another style of 
> documentation.

At the risk of making an ad hominem attack, Xah Lee's posts usually have
all the characteristics of Internet trolling. He unnecessarily cross-posts
to multiple newsgroups. He makes sweeping generalizations and inflammatory
criticisms based on little understanding. He frequently uses abusive
language. He tries to critique Python as an expert, and yet frequently
makes silly newbie mistakes or displays ignorance of some very basic
Python features.

http://en.wikipedia.org/wiki/Internet_troll
http://www.teamtechnology.co.uk/troll.htm


-- 
Steven.


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


Re: What is different with Python ?

2005-06-18 Thread Andrea Griffini
On 18 Jun 2005 00:26:04 -0700, "Michele Simionato"
<[EMAIL PROTECTED]> wrote:

>Your position reminds me of this:
>
>http://www.pbm.com/~lindahl/real.programmers.html

Yeah, but as I said I didn't use a TRS-80, but an
Apple ][. But the years were those ;-)

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


  1   2   >