Re: keyword in package name.

2008-10-19 Thread Tino Wildenhain

Abhishek Mishra wrote:

Hello Everyone,

I have the habit of using domain names (of either the application or
company) in reverse in package names.

for e.g. com.spam.app1


While this seemed a good idea for java, I don't think it makes
sense for python - the reason: in python you have an import
mechanism, where in java you just have namespaces.

Therefore you can always avoid namespace clashes at import time.

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-19 Thread Aaron Brady
Steven D'Aprano wrote:

> On Sun, 19 Oct 2008 02:52:52 +, Aaron Brady wrote:
>
>> Steven D'Aprano wrote:
>> 
>>> On Sat, 18 Oct 2008 09:17:28 +1300, Lawrence D'Oliveiro wrote:
>>>
 In message
 <[EMAIL PROTECTED]>,
 Aaron "Castironpi" Brady wrote:
 
> The purpose of a parameter is something that the caller can supply,
> but doesn't have to.  It is not for internal-use-only items.
 
 Exactly!
>>>
>>> Says who?
>>>
>>> Using arguments for internal-use-only is a perfectly acceptable example
>>> of practicality beating purity.
>> 
>> That's a stretch.
>
>
> It's a standard Python idiom used by the standard library.
>

It's a compromise solution, where the other compromises are about as
good.

...Except for the confused newbies.  But why should they pick this
feature to ignore the documentation for?  It trades off intuitiveness
for convenience.



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


Re: ANN: pyparsing 1.5.1 released

2008-10-19 Thread Paul McGuire
On Oct 18, 1:05 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Paul McGuire wrote:
> > I've just uploaded to SourceForge and PyPI the latest update to
> > (Python 3.0 uses syntax for catching exceptions that is incompatible
> > with Python versions pre 2.6, so there is no way for me to support
> > both existing Python releases and Python 3.0 with a common source code
> > base.
>
> I thought 2to3.py was supposed to make that change automatically. Have
> you tried it and found it not to work?
>
> tjr

Please re-read my caveat.  What I said was (or tried to anyway) was
that I cannot write a source file that will work on 2.4, 2.5, 2.6, and
3.0.  Actually, it was very close - but for the change in the "except"
syntax, I could actually have pulled it off.

I should probably use 2to3.py on my unit tests, so that my Py3 version
of pyparsing can get tested more fully.  I'll also use 2to3.py on
pyparsing.py itself, it will make it easier to maintain the Py3 source
version.  (I'll still have to keep and support two different source
versions though, pity.)

-- Paul


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


Re: Python certification

2008-10-19 Thread Python Nutter
Yeah. The day Python goes Certification required to get a job is the day I
quit Python forever and move on to another language.

Certification prooves you're an idiot who needs to spend money to work
for another idiot who doesn't know enough about programming to know if
they hire competent programmers and need an idiot paper to make them
feel better and sleep better at night.

2008/10/18 Lawrence D'Oliveiro <[EMAIL PROTECTED]>:
> In message <[EMAIL PROTECTED]>, Ben Finney wrote:
>
>> srinivasan srinivas <[EMAIL PROTECTED]> writes:
>>
>>> I m planning to do certification in Python??
>>
>> Why the question marks? Are you asking us whether this is true?
>
> Perhaps he's one of those people who end sentences with a rising inflection?
> Found among Australasians, possibly elsewhere?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: xor: how come so slow?

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 16:38:37 +1300, Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Steven D'Aprano
> wrote:
> 
>> On Sat, 18 Oct 2008 09:16:11 +1300, Lawrence D'Oliveiro wrote:
>> 
>>> Data can come in fractional bits. That's how compression works.
>> 
>> If you don't believe me, try compressing a single bit and see if you
>> get a "fractional bit".
> 
> If both states of the bit are not equally likely, then you do indeed
> have a fractional bit, since
> 
> nrbits = (- logbase2(P[bit = 0]) - logbase2(P[bit = 1])) / 2


That's an arithmetic mean of the logarithms. It doesn't imply that there 
are fractional bits any more than an average family having 2.3 children 
implies that there are 0.3 of a child wandering around the streets.

Using the Shannon measure of information, you can have messages which 
contain fractional information (technically, "surprisal"), when measured 
in bits. But that doesn't imply the existence of fractional bits. Look at 
it this way: consider a barter economy where I agree to swap 5 chickens 
for 2 axes. So each axe is equivalent to 2.5 chickens. But that doesn't 
imply that there is such a thing as 0.5 of a chicken -- at least not a 
*live* chicken. While I can blithely talk about bartering fractional 
chickens, in practice when I actually go to make good on my promise, it 
must be an integer number of chickens.

Similarly, we can talk about messages containing fractional bits of 
information, but when we actually store or transmit that message in 
practice, we can only use integer numbers of bits.

As Wikipedia puts it:

It is important to differentiate between the use of "bit" in referring to 
a discrete storage unit and the use of "bit" in referring to a 
statistical unit of information. The bit, as a discrete storage unit, can 
by definition store only 0 or 1. A statistical bit is the amount of 
information that, on average[citation needed], can be stored in a 
discrete bit. ... If these two ideas need to be distinguished, sometimes 
the name bit is used when discussing data storage while shannon is used 
for the statistical bit.

http://en.wikipedia.org/wiki/Bit



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


Re: Linux.com: Python 3 makes a big break

2008-10-19 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, Kay
Schluehr wrote:

> If someone had solved the hard problem of finding a less
> cumbersome way of writing sys.stdout.write(...) ...

I don't see what the big deal is. I regularly write things like

   sys.stdout.write \
  (
""
"%(title)s\n"
  # using LABEL lets user click on text to select button
%
  {
"name" : EscapeHTML(Name),
"value" : EscapeHTML(Value),
"title" : Title,
"checked" : ("", " CHECKED")[Checked],
  }
  )

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


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread Stef Mientki

Lawrence D'Oliveiro wrote:

In message <[EMAIL PROTECTED]>, Dotan
Cohen wrote:

  

I often see mention of SMBs that either want to upgrade their Windows
installations, or move to Linux, but cannot because of inhouse VB
apps.



Probably best to leave those legacy VB apps alone and develop new
replacements in a more open, cross-platform language, like Python.
  

Sorry but for GUI design, Python is pre-historic ;-)
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: loops

2008-10-19 Thread Steven D'Aprano
On Sat, 18 Oct 2008 20:45:47 -0700, John Machin wrote:

> On Oct 19, 2:30 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
> [snip]
>> making your code easy to read and easy to maintain is far more
>> important.
>>
>> for x in (2**i for i in xrange(10)):
>>     print x
>>
>> will also print 1, 2, 4, 8, ... up to 1000.
> 
> I would say up to 512; perhaps your understanding of "up to" differs
> from mine.

Well, mine is based on Python's half-open semantics: "up to" 1000 doesn't 
include 1000, and the highest power of 2 less than 1000 is 512.

Perhaps you meant "up to and including 512".



> Easy to read? I'd suggest this:
> 
> for i in xrange(10):
> print 2 ** i


Well, sure, if you want to do it the right way *wink*. 

But seriously, no, that doesn't answer the OP's question. Look at his 
original code (which I assume is C-like pseudo-code):

for x=1;x<=100;x+x:
print x

The loop variable i takes the values 1, 2, 4, 8, etc. That's what my code 
does. If he was asking how to write the following in Python, your answer 
would be appropriate:

for x=1;x<=100;x++:
print 2**x



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


Re: default value in __init__

2008-10-19 Thread Paul McGuire
On Oct 14, 1:36 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
> > Well... How to say.. Is there any chance these people will read anything
> > *at all* ?
>
> No. That's exactly the point! Basic Python is so transparent that
> you can start using it without reading anything, just looking at
> a few examples. _Because_ of that it's their responsibility to
> ensure that if you look at a few examples you then have a complete
> understanding of the language.
>
I agree, Python really does strive to be intuitive and easy-to-learn.
So the oddity of the behavior of "optional_list_arg=[]" is a recurring
surprise to those who jump first and read documentation later.
Besides the tutorials, reference docs, and FAQs, there are also some
web pages with titles like "Python Gotchas" and "Common Mistakes in
Python" that usually tread this ground too.

> In particular default parameters should work the way the user
> expects! The fact that different users will expect different
> things here is no excuse...
>
Are you being sarcastic?  Short of "import mindreading", I don't know
how Python would know which behavior a given user would expect.  Maybe
instead of a "code smell", this particular Python wart is a "design
smell".

What is surprising is that Python cannot discriminate between this:
y = 100
def f(a,x=y):
  print a+x
>>> f(1)
101
>>> y=200
>>> f(1)
101

and this:

def f(a,x=[]):
  print a+len(x)
  x.append(a)
>>> f(1)
1
>>> f(1)
2
>>> f(1,[1,2,3])
4
>>>

Is x supposed to be a default arg or a "static" arg (in the sense of a
static var within a function as one finds in C)?

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


Re: Linux.com: Python 3 makes a big break

2008-10-19 Thread Steven D'Aprano
On Sat, 18 Oct 2008 21:34:13 -0700, Kay Schluehr wrote:

> On 18 Okt., 22:01, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> 
>> Perhaps it also omitted the fact that nothing prevents you from
>> defining a function to write things to stdout (or elsewhere) in Python
>> 2.5, making the Python 3.x change largely a non-feature. ;)
>>
>> Jean-Paul
> 
> Even more. If someone had solved the hard problem of finding a less
> cumbersome way of writing sys.stdout.write(...) the request for
> multiline lambdas ( multi expression lambdas actually ) could have been
> decreased about 75-80%.


Er, am I missing something? How about this?

import sys
pr = sys.stdout.write

pr('Is this less cumbersome enough for you?')

But of course, that doesn't really help you avoid multi-expression 
lambdas, unless you want to write obfuscated code:

def foo(x):
y = x+1
print y
return y

is roughly, but inefficiently, equivalent to:

lambda x: sys.stdout.write(x+1) or x+1

But that's cumbersome and obfuscated, and not scalable at all.



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


[ANN] pyKook 0.0.1 - a simple build tool similar to Make or Ant

2008-10-19 Thread kwatch
Hi all,

I have released pyKook 0.0.1.
http://pypi.python.org/pypi/Kook/0.0.1
http://www.kuwata-lab.com/kook/
http://www.kuwata-lab.com/kook/pykook-users-guide.html

pyKook is a simple build tool similar to Make, Ant, Rake, or SCons.
pyKook regards software project as cooking.
Terms used in pyKook are cooking terms.
For example:

cookbook-  Makefile
product -  target file
ingredient  -  source file
recipe  -  how to create target from source


Cookbook (= Makefile) is written in pure Python.
You can write any statements or expressions in cookbook.


Example of cookbook (Kookbook.py):

--
##
## properties
##
cc = prop('cc', 'gcc')
cflags = prop('cflags', '-g -Wall')


##
## recipes
##
@ingreds("hello")
def task_all(c):
pass

@product("hello")
@ingreds("hello.o")
def file_command(c):
"""generates hello command"""
system(c%"$(cc) $(cflags) -o $(product) $(ingred)")

@product("*.o")
@ingreds("$(1).c", if_exists("$(1).h"))
def file_ext_o(c):
"""compile '*.c' and '*.h'"""
system(c%"$(cc) $(cflags) -c $(1).c")

def task_clean(c):
rm_f("*.o")
--


Exampe of result:

==
sh> ls
Kookbook.py   hello.chello.h

sh> pykook -l
Properties:
  cc  : 'gcc'
  cflags  : '-g -Wall'

Task recipes:
  all : cook all products
  clean   : remove by-products

File recipes:
  hello   : generates hello command
  *.o : compile '*.c' and '*.h'

(Tips: you can set 'kook_default_product' variable in your
kookbook.)

sh> pykook all   # or, pykook --cc=gcc4 all
### *** hello.o (func=file_ext_o)
$ gcc -g -Wall -c hello.c
### ** hello (func=file_command)
$ gcc -g -Wall -o hello hello.o
### * all (func=task_all)
==


See users-guide for more details.
http://www.kuwata-lab.com/kook/pykook-users-guide.html


Have fun!

--
regards,
makoto kuwata

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


Re: xor: how come so slow?

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 04:38:04 +, Tim Roberts wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>>
>>On Fri, 17 Oct 2008 20:51:37 +1300, Lawrence D'Oliveiro wrote:
>>
>>> Is piece really meant to be random? If so, your create_random_block
>>> function isn't achieving much--xoring random data together isn't going
>>> to produce anything more exciting than less random data than you
>>> started with.
>>
>>Hmmm... why do you say that xoring random data with other random data
>>produces less randomness than you started with?
>>
>>I'm not saying that you're wrong, and certainly it is pointless since
>>you're not going to improve on the randomness of /dev/urandom without a
>>lot of work. But less random?
> 
> For those who got a bit lost here, I'd would point out that Knuth[1] has
> an excellent chapter on random numbers that includes a detailed
> discussion of this effect.  His net takeaway is that most of the things
> people do to increase randomness actually have exactly the opposite
> effect.

I don't doubt it at all. But xoring random data with more random data? 
I'm guessing that if the two sources of data are independent and from the 
same distribution, then xoring them is pointless but not harmful. Here's 
a rough-and-ready test which suggests there's little harm in it:


>>> import os, math
>>> def rand_data(size):
... return [ord(c) for c in os.urandom(size)]
...
>>> def mean(data):
... return sum(data)/len(data)
...
>>> def stdev(data):
... return math.sqrt( mean([x**2 for x in data]) - mean(data)**2 )
...
>>> A = rand_data(1000)  # good random data
>>> B = rand_data(1000)  # more good random data
>>> AB = [a^b for (a,b) in zip(A, B)]  # is this still good random data?
>>> assert len(AB) == len(A) == len(B)
>>>
>>> mean(A), stdev(A)
(126, 73.91887445030531)
>>> mean(B), stdev(B)
(128, 74.242844773082339)
>>> mean(AB), stdev(AB)
(129, 74.39085965358916)


Note: I wouldn't take the above terribly seriously. Mean and standard 
deviation alone are terrible measures of the randomness of data. But this 
does suggest that any deviation from uniform randomness will be quite 
subtle.



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


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread Dotan Cohen
2008/10/19 Stef Mientki <[EMAIL PROTECTED]>:
> Sorry but for GUI design, Python is pre-historic ;-)
> Stef

Really, even with the cross-platform Qt bindings?

Can you recommend a better language? (not java no please not java)

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: keyword in package name.

2008-10-19 Thread Abhishek Mishra
On Oct 19, 12:11 pm, Tino Wildenhain <[EMAIL PROTECTED]> wrote:
> Abhishek Mishra wrote:
> > Hello Everyone,
>
> > I have the habit of using domain names (of either the application or
> > company) in reverse in package names.
>
> > for e.g. com.spam.app1
>
> While this seemed a good idea for java, I don't think it makes
> sense for python - the reason: in python you have an import
> mechanism, where in java you just have namespaces.
>
> Therefore you can always avoid namespace clashes at import time.
>
Hi,

Thanks for your reply on a Sunday!

Here's my 2 cents on why I prefer this mechanism -

I would like not to worry about namespace clashes at import time.
Using a toplevel package which isolates your namespace from all
others, is a good idea in my opinion.
This could be a product name (like MoinMoin in MoinMoin), company name
(like google in google app engine - which is just one short of
com.google btw), or your DNS.
Therefore I use a domain name lots of times. (I admit that I picked up
this habit from programming a lot in java).

Although it looks like in this case I would have to use just the
project name.

Thanks & Regards,
Abhishek Mishra




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


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread Stef Mientki

Dotan Cohen wrote:

2008/10/19 Stef Mientki <[EMAIL PROTECTED]>:
  

Sorry but for GUI design, Python is pre-historic ;-)
Stef



Really, even with the cross-platform Qt bindings?
  

I skipped Qt because of the weird license
(I make both commercial and free-open software)

Can you recommend a better language? (not java no please not java)

  

As said VB or even much better Delphi !

But to be honest,
wanting the same language for commercial and open software,
I'm very satisfied with Python, and  must say it's much more beautiful 
language than Delphi, seen over the full width of programming.

Although both languages are Object Oriented,
for some (unknown) reason it's 10 times easier to maintain and extend 
libraries in Python than in Delphi.

I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE !
And with wxPython and some tools I made, I almost have the same 
environment as Delphi.



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


Re: Help with Iteration

2008-10-19 Thread Hendrik van Rooyen
Aaron Brady  wrote:

>while 1:
>calculate_stuff( )
>if stuff < 0.5:
>break

The thought police will come and get you.

You are doing things by "side effect"!
You are using a global called "stuff"!
You are relying on an implementation
detail!

While their cudgels are bouncing off
your skull, they will scream the above three
lines into your swiftly swelling ears!

I suggest you write;

while True:
stuff = calculate_stuff()
if stuff < 0.5:
break

quickly, to avoid the pain!

It may be too late though - even the
above sanitised version is still too
tightly coupled - how must
calculate_stuff know where to find
the inputs for its calculation?

You are gonna bleed!

:-)

- Hendrik

--
No good deed will go unpunished.



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


Re: keyword in package name.

2008-10-19 Thread Marc 'BlackJack' Rintsch
On Sat, 18 Oct 2008 23:05:38 -0700, Abhishek Mishra wrote:

> I have the habit of using domain names (of either the application or
> company) in reverse in package names.
> 
> for e.g. com.spam.app1
> 
> I've recently started a project for an indian domain (tld = .in), which
> leads to a package name like
> 
> in.spam.app1
> 
> This causes a syntax error, as "in" is a keyword. I understand that this
> is an unfortunate "feature", but has anyone faced this problem before,
> and is there a possible workaround.

`com_spam.app1`!?  I would even recommend this with domains that don't 
clash with keywords because if several people start to use this package 
name convention you will get name clashes at package level.  Say there 
are two vendors with a `com` TLD, how do you install their packages?  
Into the same `com/` subdirectory?  The `__init__.py` of which vendor 
should live at the `com/` directory level?  If you install them into two 
different directories but want to import modules from both vendors -- how?

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-10-19 Thread Steven D'Aprano
On Fri, 17 Oct 2008 16:36:24 -0400, Steve Holden wrote:

> People here don't describe Python as different just because they *want*
> it to be different. Python acknowledges intellectual debts to many
> languages, none of which is exactly like it.

I understand that Python's object and calling semantics are exactly the 
same as Emerald (and likely other languages as well), and that both 
Emerald and Python are explicitly based on those of CLU, as described by 
by Barbara Liskov in 1979:

"In particular it is not call by value because mutations 
 of arguments performed by the called routine will be 
 visible to the caller. And it is not call by reference 
 because access is not given to the variables of the 
 caller, but merely to certain objects."

http://www.lcs.mit.edu/publications/pubs/pdf/MIT-LCS-TR-225.pdf

quoted by Fredrik Lundh here:
http://mail.python.org/pipermail/python-list/2003-May/204379.html


"Call by object/sharing" isn't some new-fangled affectation invented by 
comp.lang.python dweebs to make Python seem edgy and different. It's a 
term that has been in use in highly respected Comp Sci circles for over 
thirty years. In case anybody doesn't recognise the name:

http://en.wikipedia.org/wiki/Barbara_Liskov


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


Re: keyword in package name.

2008-10-19 Thread Terry Reedy

Abhishek Mishra wrote:

Hello Everyone,

I have the habit of using domain names (of either the application or
company) in reverse in package names.

for e.g. com.spam.app1

I've recently started a project for an indian domain (tld = .in),
which leads to a package name like

in.spam.app1

This causes a syntax error, as "in" is a keyword.


india = __import__('in')
will work
while you must alias in Python, you can have what you want on disk

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


Re: default value in __init__

2008-10-19 Thread Chris Rebert
On Sun, Oct 19, 2008 at 12:56 AM, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Oct 14, 1:36 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
>> > Well... How to say.. Is there any chance these people will read anything
>> > *at all* ?
>>
>> No. That's exactly the point! Basic Python is so transparent that
>> you can start using it without reading anything, just looking at
>> a few examples. _Because_ of that it's their responsibility to
>> ensure that if you look at a few examples you then have a complete
>> understanding of the language.
>>
> I agree, Python really does strive to be intuitive and easy-to-learn.
> So the oddity of the behavior of "optional_list_arg=[]" is a recurring
> surprise to those who jump first and read documentation later.
> Besides the tutorials, reference docs, and FAQs, there are also some
> web pages with titles like "Python Gotchas" and "Common Mistakes in
> Python" that usually tread this ground too.

Specifically:
http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html?page=2
http://www.ferg.org/projects/python_gotchas.html#contents_item_6
http://zephyrfalcon.org/labs/python_pitfalls.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
>> In particular default parameters should work the way the user
>> expects! The fact that different users will expect different
>> things here is no excuse...
>>
> Are you being sarcastic?  Short of "import mindreading", I don't know
> how Python would know which behavior a given user would expect.  Maybe
> instead of a "code smell", this particular Python wart is a "design
> smell".
>
> What is surprising is that Python cannot discriminate between this:
> y = 100
> def f(a,x=y):
>  print a+x
 f(1)
> 101
 y=200
 f(1)
> 101
>
> and this:
>
> def f(a,x=[]):
>  print a+len(x)
>  x.append(a)
 f(1)
> 1
 f(1)
> 2
 f(1,[1,2,3])
> 4

>
> Is x supposed to be a default arg or a "static" arg (in the sense of a
> static var within a function as one finds in C)?
>
> -- Paul
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread Dotan Cohen
2008/10/19 Stef Mientki <[EMAIL PROTECTED]>:
> Dotan Cohen wrote:
>>
>> 2008/10/19 Stef Mientki <[EMAIL PROTECTED]>:
>>
>>>
>>> Sorry but for GUI design, Python is pre-historic ;-)
>>> Stef
>>>
>>
>> Really, even with the cross-platform Qt bindings?
>>
>
> I skipped Qt because of the weird license
> (I make both commercial and free-open software)
>>
>> Can you recommend a better language? (not java no please not java)
>>
>>
>
> As said VB or even much better Delphi !
>
> But to be honest,
> wanting the same language for commercial and open software,
> I'm very satisfied with Python, and  must say it's much more beautiful
> language than Delphi, seen over the full width of programming.
> Although both languages are Object Oriented,
> for some (unknown) reason it's 10 times easier to maintain and extend
> libraries in Python than in Delphi.
> I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE !
> And with wxPython and some tools I made, I almost have the same environment
> as Delphi.
>

Really, you recommend that VB apps destined for migration be recoded
in Delphi, as opposed to Python? I will look further into that
language.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


urllib2.HTTPError: HTTP Error 204: NoContent

2008-10-19 Thread silk.odyssey
I am getting the following error trying to download an html page using
urllib2.

urllib2.HTTPError: HTTP Error 204: NoContent

The url is of this type:

http://www.amazon.com/gp/offer-listing/B000KJX3A0%3FSubscriptionId%3D183VXJS74KNQ89D0NRR2%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000KJX3A0

I can open it in my browser without problems.Any ideas on a solution?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread Francesco Bochicchio
Il Sun, 19 Oct 2008 10:34:23 +0200, Stef Mientki ha scritto:

...

 I'm very
> satisfied with Python, and  must say it's much more beautiful language
> than Delphi, seen over the full width of programming. Although both
> languages are Object Oriented, for some (unknown) reason it's 10 times
> easier to maintain and extend libraries in Python than in Delphi.
> I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE ! And
> with wxPython and some tools I made, I almost have the same environment
> as Delphi.
> 

IMO:
- dynamic typing
- powerful built-in types like lists, sets and dictionaries
- very rich function definition syntax, with multiple returns,
  yield, values passed by position and by name, automatic
  grouping of parameters in list/dictionaries
- rich standard library, which becomes impressive if you accound for all
  the non standard modules that you find in internet. And, unlike another
  language wich shall remain unnamed (starts with J), most of python
  library modules have the same pratical approach of C standard
  library. 

Never used seriously delphi, but played a little with it: IIRC, under the 
nice IDE and GUI toolkit, the language itself is a kind of object-pascal.
This would place it more or less at the same level of abstraction of 
Java,  way below  languages like python and ruby, 


Ciao
-
FB

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


Re: Normalizing arguments

2008-10-19 Thread Dan Ellis
On Oct 17, 7:16 pm, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:

> George Sakkis has a recipe that might help.
>
> http://code.activestate.com/recipes/551779/

Looks like just the thing. Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: loops

2008-10-19 Thread John Machin


Steven D'Aprano wrote:

> On Sat, 18 Oct 2008 20:45:47 -0700, John Machin wrote:
>
> > On Oct 19, 2:30 pm, Steven D'Aprano <[EMAIL PROTECTED]
> > cybersource.com.au> wrote:
> > [snip]
> >> making your code easy to read and easy to maintain is far more
> >> important.
> >>
> >> for x in (2**i for i in xrange(10)):
> >>     print x
> >>
> >> will also print 1, 2, 4, 8, ... up to 1000.
> >
> > I would say up to 512; perhaps your understanding of "up to" differs
> > from mine.
>
> Well, mine is based on Python's half-open semantics: "up to" 1000 doesn't
> include 1000, and the highest power of 2 less than 1000 is 512.

We're talking about an English sentence, not a piece of Python code.
When you say "I'm taking the train to X", do you get off at the
station before X, as in "getting off at Redfern"?


>
> Perhaps you meant "up to and including 512".
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread Stef Mientki

Dotan Cohen wrote:

2008/10/19 Stef Mientki <[EMAIL PROTECTED]>:
  

Dotan Cohen wrote:


2008/10/19 Stef Mientki <[EMAIL PROTECTED]>:

  

Sorry but for GUI design, Python is pre-historic ;-)
Stef



Really, even with the cross-platform Qt bindings?

  

I skipped Qt because of the weird license
(I make both commercial and free-open software)


Can you recommend a better language? (not java no please not java)


  

As said VB or even much better Delphi !

But to be honest,
wanting the same language for commercial and open software,
I'm very satisfied with Python, and  must say it's much more beautiful
language than Delphi, seen over the full width of programming.
Although both languages are Object Oriented,
for some (unknown) reason it's 10 times easier to maintain and extend
libraries in Python than in Delphi.
I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE !
And with wxPython and some tools I made, I almost have the same environment
as Delphi.




Really, you recommend that VB apps destined for migration be recoded
in Delphi, as opposed to Python? 

Certainly not.
Delphi is windows only and as Francesco said,
it's just Object Pascal , which is inferior to Python.

Stef


I will look further into that
language.

  


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


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread Stef Mientki

Francesco Bochicchio wrote:

Il Sun, 19 Oct 2008 10:34:23 +0200, Stef Mientki ha scritto:

...

 I'm very
  

satisfied with Python, and  must say it's much more beautiful language
than Delphi, seen over the full width of programming. Although both
languages are Object Oriented, for some (unknown) reason it's 10 times
easier to maintain and extend libraries in Python than in Delphi.
I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE ! And
with wxPython and some tools I made, I almost have the same environment
as Delphi.




IMO:
- dynamic typing
- powerful built-in types like lists, sets and dictionaries
- very rich function definition syntax, with multiple returns,
  yield, values passed by position and by name, automatic
  grouping of parameters in list/dictionaries
- rich standard library, which becomes impressive if you accound for all
  the non standard modules that you find in internet. And, unlike another
  language wich shall remain unnamed (starts with J), most of python
  library modules have the same pratical approach of C standard
  library. 

Never used seriously delphi, but played a little with it: IIRC, under the 
nice IDE and GUI toolkit, the language itself is a kind of object-pascal.
This would place it more or less at the same level of abstraction of 
Java,  way below  languages like python and ruby, 
  

Thanks Francesco,
for these features and indeed the Object Pascal language is indeed 
inferior to Python.

Some of Python features that I find an enormous improvement over Delphi:
- extending functions and classes with keyword arguments, without 
affecting the previous use of these declarations

- array slicing
- having 1 procedure that can handle every type, opposed to the Delphi 
overload method


Some minor points of Python, compared to Delphi
- rich standard library is less than in Delphi. It might be just as 
large, but using it is a crime (Delphi libs always work because they are 
upwards compatible)

- GUI design
- deploying an application

cheers,
Stef



Ciao
-
FB

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


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


Re: keyword in package name.

2008-10-19 Thread Abhishek Mishra
On Oct 19, 2:06 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> `com_spam.app1`!?  I would even recommend this with domains that don't
> clash with keywords because if several people start to use this package
> name convention you will get name clashes at package level.  Say there
> are two vendors with a `com` TLD, how do you install their packages?  
> Into the same `com/` subdirectory?  The `__init__.py` of which vendor
> should live at the `com/` directory level?  If you install them into two
> different directories but want to import modules from both vendors -- how?
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Ah, you have opened my eyes.
I should have asked myself before why I did not face such a clash.
(because no-one uses this convention!)

I guess the way to go is not use the tld, but just a unique company/
product name.

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


Re: Finding the instance reference of an object

2008-10-19 Thread Steven D'Aprano
On Fri, 17 Oct 2008 09:56:17 -0600, Joe Strout wrote:

> On Oct 16, 2008, at 11:23 PM, Dennis Lee Bieber wrote:
> 
>> On Thu, 16 Oct 2008 21:19:28 -0600, Joe Strout <[EMAIL PROTECTED]>
>> declaimed the following in comp.lang.python:
>>
>>> Now that IS mysterious.  Doesn't calling a function add a frame to a
>>> stack?  And doesn't that necessitate copying in values for the
>>> variables in that stack frame (such as 'x' above)?  Of course we're
>>
>>No -- it copies the /reference/ to the object containing the value.
> 
> The reference to the object IS the value of an object reference
> variable.  

That's a bizarre and unnatural way of looking at it. To steal a line from 
the effbot, that's like valuing your child's Social Security number over 
the child herself:

http://mail.python.org/pipermail/python-list/2003-May/204560.html


If we execute a line of Python code:

x = "parrot"

and then ask "What's the value of x?", I think that even you would think 
I was being deliberately obtuse, difficult and obfuscatory if I answered 
"location 0xb7cdeb2c".


> So good, parameters are passed ByVal in Python as they appear
> to be, and as is the default in every other modern language.

Nonsense. Python doesn't copy a parameter before passing it to the 
function. You get the same parameter inside the function as outside:

>>> def foo(x):
... print id(x)
...
>>> a = ['some', 'thing']
>>> print id(a); foo(a)
3083441036
3083441036


I'm going to anticipate your response here: you're going to deny that 
call by value implies that the list ['some', 'thing'] will be copied 
before being passed to the function. According to *some* definitions of 
CBV, you might even be right. But according to *other* definitions, 
including the one that I learned in comp sci at university, that copying 
of data is an essential part of CBV.

These other definitions aren't necessarily a formal definition from some 
Computer Scientist. They're just as likely to be informal understandings 
of what CBV and CBR mean: "if it's call by value, don't pass big data 
structures because they will be copied and your code will be slow".


>> Just as assignment transfers the reference to the RHS object to the
>> name
>> shown on the LHS.
> 
> Assignment copies the RHS value to the LHS variable.  In the case of an
> object reference, the value copied is, er, an object reference.

No, assignment binds an object to a name. That's what Python does.

Of course, at the implementation level, name binding might be implemented 
by copying object references. Or it might not. That's an implementation 
detail that isn't relevant at the Python level.

Or at least, it shouldn't be relevant until the abstraction leaks.
http://www.joelonsoftware.com/articles/LeakyAbstractions.html



[snip]
> For object references (including the mutable ones that may treat people
> up), Python's behavior is no different from any other language.

That's an exceedingly broad claim. No different from Java? Well, perhaps. 
No different from Lisp? Doubtful. No different from Forth? Yeah, riiight.

Speaking of Java, there's one major difference between Java and Python 
with respect to names. In a statically typed language like Java, you 
define names before you use them, and from that point the name is bound 
to both a type and an object. But the binding to the object is optional, 
and such unbound names are said to be null.

In a dynamically typed language like Python, names are bound only to 
objects. You can't have an unbound name: if a name exists, it must be 
bound to an object, and if it doesn't exist, you get a NameError 
exception when you try to access it. And objects are typed, not names.

http://www.ferg.org/projects/python_java_side-by-side.html



 
 (Answer: neither. They are call by name.)
>>>
>>> I have no idea what that means.  They're call by value as far as I can
>>> tell.  (Even if the value may happen to be a reference.)
>>
>>  Technically, as I recall the definition of "call by name", they
>> aren't that either. ...
>> Call by name, then, acted as a macro expansion wherever the argument
>> was referenced in the called function.
> 
> Thanks for that explanation.  Clearly that's not what's going on in
> Python.

Ah no, that's my bad. I have a strange and disturbing mental stutter that 
substitutes "call by name" when I mean to say "call by object" at the 
most embarrassing times. Sorry.




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


Re: default value in __init__

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 00:56:17 -0700, Paul McGuire wrote:
> On Oct 14, 1:36 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
...
>> In particular default parameters should work the way the user expects!
>> The fact that different users will expect different things here is no
>> excuse...
>>
> Are you being sarcastic? 

Yes, David was being sarcastic. Or possibly ironic. Satirical? One of 
those humour things. Whatever it was, I think you're the second person 
who missed it. 


> Short of "import mindreading", I don't know
> how Python would know which behavior a given user would expect.

Exactly.

Besides, Guido has a time machine, and apparently antigravity is being 
added to the standard library, so I don't see why we can't have 
mindreading too.




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


Re: keyword in package name.

2008-10-19 Thread Diez B. Roggisch

Abhishek Mishra schrieb:

On Oct 19, 2:06 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

`com_spam.app1`!?  I would even recommend this with domains that don't
clash with keywords because if several people start to use this package
name convention you will get name clashes at package level.  Say there
are two vendors with a `com` TLD, how do you install their packages?  
Into the same `com/` subdirectory?  The `__init__.py` of which vendor

should live at the `com/` directory level?  If you install them into two
different directories but want to import modules from both vendors -- how?

Ciao,
Marc 'BlackJack' Rintsch


Ah, you have opened my eyes.
I should have asked myself before why I did not face such a clash.
(because no-one uses this convention!)

I guess the way to go is not use the tld, but just a unique company/
product name.


I personally tend to mix the approaches. Using setuptools, you can 
declare so-called "namespace-packages".


I use one of these for all my projects at work. It is derived from the 
companyname, and thus is unique. And all sub-packages for the various 
projects can have names that describe them and sometimes would clash 
with other projects (e.g. devtools, which also is a TurboGears-package)


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


Re: loops

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 03:17:51 -0700, John Machin wrote:

> Steven D'Aprano wrote:
> 
>> On Sat, 18 Oct 2008 20:45:47 -0700, John Machin wrote:
>>
>> > On Oct 19, 2:30 pm, Steven D'Aprano <[EMAIL PROTECTED]
>> > cybersource.com.au> wrote:
>> > [snip]
>> >> making your code easy to read and easy to maintain is far more
>> >> important.
>> >>
>> >> for x in (2**i for i in xrange(10)):
>> >>     print x
>> >>
>> >> will also print 1, 2, 4, 8, ... up to 1000.
>> >
>> > I would say up to 512; perhaps your understanding of "up to" differs
>> > from mine.
>>
>> Well, mine is based on Python's half-open semantics: "up to" 1000
>> doesn't include 1000, and the highest power of 2 less than 1000 is 512.
> 
> We're talking about an English sentence, not a piece of Python code.
> When you say "I'm taking the train to X", do you get off at the station
> before X, as in "getting off at Redfern"?

But I don't say "I'm taking the train UP TO X".

Intervals in English are often ambiguous, which is why people often 
explicitly say "up to and including...". But in this specific case, I 
don't see why you're having difficulty. Whether 1000 was included or not 
makes no difference, because 1000 is not a power of 2.


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


What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Stef Mientki

hello,

I (again) wonder what's the perfect way to store, OS-independent, 
filepaths ?

I can think of something like:
- use a relative path if drive is identical to the application (I'm 
still a Windows guy)

- use some kind of OS-dependent translation table if on another drive
- use ? if on a network drive

I'm interested what you all use for this kind of problem.
And I wonder why there isn't a standard solution / library in Python 
available.


thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: a new brawser (avant) it is very very good

2008-10-19 Thread Stef Mientki

mina2020 wrote:
what has this todo with Python ?

Avant Browser allows users to browse multiple Web sites simultaneously
and to block all unwanted pop-up pages and Flash ads automatically.
The integrated cleaner helps users clear all traces and maintain
privacy. The built-in Yahoo and Google search engines enable users to
search for Web pages, images, groups, directories, lyrics, software,
and news on the Internet. Avant Browser provides options for blocking
the download of Flash media, pictures, video, sounds, and ActiveX
components, so users can efficiently use their bandwidth and speed up
page loading. All opened pages can be stopped, refreshed, closed, or
arranged with one click. It also comes with built-in RSS reader. Its
similar Web sites bar displays Web sites, which are related to the
opened Web pages.
download
http://m-google-adsense.blogspot.com/2008/10/what-is-google-adsense.html
--
http://mail.python.org/mailman/listinfo/python-list
  


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


Re: inserting Unicode character in dictionary - Python

2008-10-19 Thread Joe Strout

On Oct 18, 2008, at 1:20 AM, Martin v. Löwis wrote:


Do you then have a proper UTF-8 string,
but the problem is that none of the standard Python library methods  
know

how to properly interpret UTF-8?


There is (probably) no such thing as a "proper UTF-8 string" (in the
sense in which you probably mean it).


To be clear, I mean a string that is valid UTF-8 (not all strings of  
bytes are, of course).



Python doesn't have a data type
for "UTF-8 string". It only has a data type "byte string". It's up to
the application whether it gets interpreted in a consistent manner.
Libraries are (typically) encoding-agnostic, i.e. they work for UTF-8
encoded strings the same way as for, say, Big-5 encoded strings.


Oi -- so if I ask for length, I get the number of bytes, not the  
number of characters.  If I slice and dice, I could end up splitting  
characters in half.  It is, as you say, just a string of bytes, not a  
string of characters.



4. In Python 3.0, this silliness goes away, because all strings are
Unicode by default.


You still need to make sure that the editor's encoding and the  
declared

encoding match.


Well, the if no encoding is declared, it (quite sensibly) assumes  
UTF-8, so for my purposes this boils down to using a UTF-8 editor --  
which I always do anyway.  But do I still have to put a "u" before my  
string literals in order to have it treated as characters rather than  
bytes?


I'm hoping that the answer is "no" -- most string literals in a source  
file are text (which should be Unicode text, these days); a raw byte  
string would be the exceptional case, and I'd be happy to use the "r"  
prefix for those.


Best,
- Joe

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


Re: ANN: pyparsing 1.5.1 released

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

> On Oct 18, 1:05 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
>> Paul McGuire wrote:
>> > I've just uploaded to SourceForge and PyPI the latest update to
>> > (Python 3.0 uses syntax for catching exceptions that is
>> > incompatible with Python versions pre 2.6, so there is no way for
>> > me to support both existing Python releases and Python 3.0 with a
>> > common source code base.
>>
>> I thought 2to3.py was supposed to make that change automatically.
>> Have you tried it and found it not to work?
>>
>> tjr
> 
> Please re-read my caveat.  What I said was (or tried to anyway) was
> that I cannot write a source file that will work on 2.4, 2.5, 2.6, and
> 3.0.  Actually, it was very close - but for the change in the "except"
> syntax, I could actually have pulled it off.
> 
> I should probably use 2to3.py on my unit tests, so that my Py3 version
> of pyparsing can get tested more fully.  I'll also use 2to3.py on
> pyparsing.py itself, it will make it easier to maintain the Py3 source
> version.  (I'll still have to keep and support two different source
> versions though, pity.)
> 

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

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

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

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


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread [EMAIL PROTECTED]
On Oct 19, 8:35 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
> I (again) wonder what's the perfect way to store, OS-independent,
> filepaths ?

I don't think there is any such thing.  What problem are you trying to
solve?
--
http://mail.python.org/mailman/listinfo/python-list


Re: keyword in package name.

2008-10-19 Thread MRAB
On Oct 19, 7:05 am, Abhishek Mishra <[EMAIL PROTECTED]> wrote:
> Hello Everyone,
>
> I have the habit of using domain names (of either the application or
> company) in reverse in package names.
>
> for e.g. com.spam.app1
>
> I've recently started a project for an indian domain (tld = .in),
> which leads to a package name like
>
> in.spam.app1
>
> This causes a syntax error, as "in" is a keyword.
> I understand that this is an unfortunate "feature", but has anyone
> faced this problem before,
> and is there a possible workaround.
>
> P.S. this would also be a problem for the iceland domains (tld = .is).
> TLDs:http://data.iana.org/TLD/tlds-alpha-by-domain.txt
> Python Keywords:http://www.python.org/doc/2.5.2/ref/keywords.html
>
You could add a trailing underscore, ie "in_". This "fix" is done in
the poplib module where the POP3 class has a method called "pass_"
because "pass" is a reserved word.
--
http://mail.python.org/mailman/listinfo/python-list


indentation

2008-10-19 Thread Gandalf
every time I switch editor all the script  indentation get mixed up,
and python start giving me indentation weird errors.
indentation also  hard to follow because it invisible  unlike brackets
{ }

is there any solution to this problems?



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


Re: xor: how come so slow?

2008-10-19 Thread MRAB
On Oct 19, 7:13 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 19 Oct 2008 04:38:04 GMT, Tim Roberts <[EMAIL PROTECTED]> declaimed
> the following in comp.lang.python:
>
>
>
> > For those who got a bit lost here, I'd would point out that Knuth[1] has an
> > excellent chapter on random numbers that includes a detailed discussion of
> > this effect.  His net takeaway is that most of the things people do to
> > increase randomness actually have exactly the opposite effect.
>
>         Some decade I'll have to obtain his volumes... But they've never
> shown up in a $60 special offer from a book club (unlike the compact
> editions of the OED) .
>
>         And while XOR may seem significant, just consider die rolls...
>
>         If each "byte" were one die roll, you'd expect a nearly even
> distribution... (for a 6 sided die, 1/6 would have each value). But
> using the sum of two die, your begin to get a bell curve: 2 and 12
> appear 1/36 of the time (each), but 7 occurs 6/36 of the time. Use three
> die, and it gets worse: 3 and 18 occur 1/216, "10.5" occurs much more
> often...
>
That should be one die, two dice, etc. :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: a new brawser (avant) it is very very good

2008-10-19 Thread George Sakkis
On Oct 17, 5:59 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
> mina2020 wrote:
>
> what has this todo with Python ?

Do you take the time to reply to every spam you receive ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: indentation

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 07:16:44 -0700, Gandalf wrote:

> every time I switch editor all the script  indentation get mixed up, and
> python start giving me indentation weird errors. indentation also  hard
> to follow because it invisible  unlike brackets { }

Indentation is not invisible.

Can you really not see that this text
is indented? If so, your news program 
is seriously broken.


> is there any solution to this problems?

Discipline. Choose a standard indent and stick to it.

You can use tabs, or spaces. If you use spaces, you can choose 4 spaces, 
or 8, or any number, but whatever you choose, stick to it no matter what 
editor you use. Good editors will let you use the tab key to indent with 
spaces. Bad editors (e.g. Windows Notepad, and I feel your pain if you 
have to use it) force you to manually insert spaces.

Especially never mix tabs and spaces in the same file. If you're editing 
an existing file, you must follow whatever indent standard is already in 
use.

You can also pass the -t option when launching the Python interpreter to 
warn about mixed tabs and spaces.

See also the standard module tabnanny:

http://effbot.org/librarybook/tabnanny.htm



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


Re: Linux.com: Python 3 makes a big break

2008-10-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
Lawrence D'Oliveiro  <[EMAIL PROTECTED]> wrote:
>In message
><[EMAIL PROTECTED]>, Kay
>Schluehr wrote:
>>
>> If someone had solved the hard problem of finding a less
>> cumbersome way of writing sys.stdout.write(...) ...
>
>I don't see what the big deal is. I regularly write things like
>
>   sys.stdout.write \
>  (
>"" ID=\"%(name)s[%(value)s]\" VALUE=\"%(value)s\"%(checked)s>"
>"%(title)s\n"
>  # using LABEL lets user click on text to select button
>%
>  {
>"name" : EscapeHTML(Name),
>"value" : EscapeHTML(Value),
>"title" : Title,
>"checked" : ("", " CHECKED")[Checked],
>  }
>  )

Why are you using a backslash?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Re: Linux.com: Python 3 makes a big break

2008-10-19 Thread D'Arcy J.M. Cain
On 19 Oct 2008 07:44:52 -0700
[EMAIL PROTECTED] (Aahz) wrote:
> >   sys.stdout.write \
> >  (
> 
> Why are you using a backslash?

Because he hasn't opened the paren yet.  He could have put the open
paren on the same line as the write obviating the need for the
backslash but then his open/close parens wouldn't line up.  It just a
matter of style.

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


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 14:35:01 +0200, Stef Mientki wrote:

> hello,
> 
> I (again) wonder what's the perfect way to store, OS-independent,
> filepaths ?

"Perfect"? I can't imagine any scheme which will work on every imaginable 
OS, past present and future.

However, in practice I think there are two common forms still in use: 
Posix paths, and Windows paths. I believe that OS/2 can deal with Windows 
pathnames, and Mac OS X uses Posix paths (I think...). If you have to 
support Classic Mac OS or other non-Posix systems, then your life will 
become interesting and complicated.

And let's not even consider Unicode issues...

You might find this page useful:
http://en.wikipedia.org/wiki/Path_(computing)

Note that raw strings are for regular expressions, not Windows paths. Raw 
strings can't end in a backslash, so you can't do this:

r'C:\My Documents\'

Instead, you can avoid having to escape backslashes by taking advantage 
of the fact that Windows will accept forward slashes as well as 
backslashes as path separators, and write 'C:/My Documents/' instead.

I assume you're familiar with the path-manipulation utilities in os.path?

>>> import os
>>> os.path.splitdrive('C://My Documents/My File.txt')
('C:', 'My Documents\\My File.txt')

I had to fake the above output because I'm not running Windows, so excuse 
me if I got it wrong.

But honestly, I think your biggest problem isn't finding a platform-
independent way of storing paths, but simply translating between each 
OS's conventions on where files should be stored.

In Linux, config files should go into:

~/./ or /etc//

In Windows (which versions?) then should go into the Documents And 
Settings folder, where ever that is.

There's no single string which can represent both of these conventions!



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


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> In Linux, config files should go into:
> 
> ~/./ or /etc//
> 
> In Windows (which versions?) then should go into the Documents And 
> Settings folder, where ever that is.
> 
> There's no single string which can represent both of these conventions!

The first of those should do nicely for both Linux and Windows:

>>> os.path.normpath(os.path.expanduser('~/.appname'))
'C:\\Documents and Settings\\Duncan\\.appname'
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

 import os
 os.path.splitdrive('C://My Documents/My File.txt')
> ('C:', 'My Documents\\My File.txt')
> 
> I had to fake the above output because I'm not running Windows, so
> excuse me if I got it wrong.

Not that it matters, but:

>>> os.path.splitdrive('C://My Documents/My File.txt')
('C:', '//My Documents/My File.txt')
--
http://mail.python.org/mailman/listinfo/python-list


Re: better scheduler with correct sleep times

2008-10-19 Thread Scott David Daniels

qvx wrote:

I need a scheduler which can delay execution of a
function for certain period of time.
My attempt was something like this:  ... <<>>
Is there a better way or some library that does that?


The trick is to use Queue's timeout argument to interrupt your sleep
when new requests come in.


def time_server(commands):
'''Process all scheduled operations that arrive on queue commands'''
pending = []
while True:
now = time.time()
while pending and pending[0][0] <= now:
when, function, args, kwargs = heapq.heappop(pending)
function(*args, **kwargs)
try:
command = commands.get(timeout=pending[0][0] - now
   if pending else None)
except Queue.Empty:
pass
else:
if command is None:
break
heapq.heappush(pending, command)

queue = Queue.Queue()
thread.thread.start_new_thread(queue)
queue.put((time.time() + dt, callable, args, {}))
...

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Grant Edwards
On 2008-10-19, Stef Mientki <[EMAIL PROTECTED]> wrote:

> I (again) wonder what's the perfect way to store, OS-independent, 
> filepaths ?

The question appears to me to be meaningless. File paths are
not OS independant, so an OS-independant way to store them
doesn't seem to be a useful thing to talk about.

-- 
Grant

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


Re: Emacs users: feedback on diffs between python-mode.el and python.el?

2008-10-19 Thread dsyzling

Damien Wyart wrote:

* Carl Banks <[EMAIL PROTECTED]> in comp.lang.python:

The python-mode.el on Subversion (python-mode's Subversion on source
forge, not the ancient version of python-mode in the Python
repository) has a fix for this issue. It doesn't look like there's any
way to browse the subversion any more, though.


The viewvc interface is still there:
http://svn.sourceforge.net/viewvc/python-mode/trunk/python-mode/



I thought python-mode had moved to launchpad under bzr:
https://code.launchpad.net/python-mode.


Darren

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


Re: xor: how come so slow?

2008-10-19 Thread Steve Holden
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Steven D'Aprano
> wrote:
> 
>> On Sat, 18 Oct 2008 09:16:11 +1300, Lawrence D'Oliveiro wrote:
>>
>>> Data can come in fractional bits. That's how compression works.
>> If you don't believe me, try compressing a single bit and see if you get
>> a "fractional bit".
> 
> If both states of the bit are not equally likely, then you do indeed have a
> fractional bit, since
> 
> nrbits = (- logbase2(P[bit = 0]) - logbase2(P[bit = 1])) / 2

What's happening here is that the two different meanings of "bit" are
being confused. A bit is both a binary digit and a measure of information.

Obviously you can't create a bit stream with half a bit in it.

In a coding system where all messages of N binary digits are equally
likely then each message contains N bits of information content. This is
the theoretical upper bound on the information content.

In most practical systems, however, the messages have differing
probabilities; then an N-binary-digit message conveys less than N bits
of information, as Lawrence indicated above. Fractional bits are
perfectly valid as a measure of information content.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Finding the instance reference of an object

2008-10-19 Thread Steve Holden
Steven D'Aprano wrote:
[...]

> when you talk about "call by value 
> where the value is a reference", it sounds to me as if you are insisting 
> that cars are ACTUALLY horse and buggies, where the horse is the engine, 
> why are we inventing new terms like 'automobile', that just confuses 
> people.
> 
+1 QOTW
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: keyword in package name.

2008-10-19 Thread Steve Holden
Abhishek Mishra wrote:
> On Oct 19, 12:11 pm, Tino Wildenhain <[EMAIL PROTECTED]> wrote:
>> Abhishek Mishra wrote:
>>> Hello Everyone,
>>> I have the habit of using domain names (of either the application or
>>> company) in reverse in package names.
>>> for e.g. com.spam.app1
>> While this seemed a good idea for java, I don't think it makes
>> sense for python - the reason: in python you have an import
>> mechanism, where in java you just have namespaces.
>>
>> Therefore you can always avoid namespace clashes at import time.
>>
> Hi,
> 
> Thanks for your reply on a Sunday!
> 
> Here's my 2 cents on why I prefer this mechanism -
> 
> I would like not to worry about namespace clashes at import time.
> Using a toplevel package which isolates your namespace from all
> others, is a good idea in my opinion.
> This could be a product name (like MoinMoin in MoinMoin), company name
> (like google in google app engine - which is just one short of
> com.google btw), or your DNS.
> Therefore I use a domain name lots of times. (I admit that I picked up
> this habit from programming a lot in java).
> 
> Although it looks like in this case I would have to use just the
> project name.
> 
That will work fine until one of your top-level domains is also a
package or module on some other element of sys.path.

I can see why the convenience of a familiar naming convention might be
appealing, but you shouldn't try to stretch it beyond its natural
boundaries.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: keyword in package name.

2008-10-19 Thread Steve Holden
Marc 'BlackJack' Rintsch wrote:
> On Sat, 18 Oct 2008 23:05:38 -0700, Abhishek Mishra wrote:
> 
>> I have the habit of using domain names (of either the application or
>> company) in reverse in package names.
[...]
> The `__init__.py` of which vendor
> should live at the `com/` directory level?  If you install them into two 
> different directories but want to import modules from both vendors -- how?
> 
Obviously the "com" namespace wouldn't belong to any vendor, and the
__init__.py should be empty. Though I do think it's an inappropriate
choice for Python.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Help with Iteration

2008-10-19 Thread Steve Holden
Hendrik van Rooyen wrote:
> Aaron Brady  wrote:
> 
>> while 1:
>>calculate_stuff( )
>>if stuff < 0.5:
>>break
> 
> The thought police will come and get you.
> 
> You are doing things by "side effect"!
> You are using a global called "stuff"!
> You are relying on an implementation
> detail!
> 
> While their cudgels are bouncing off
> your skull, they will scream the above three
> lines into your swiftly swelling ears!
> 
> I suggest you write;
> 
> while True:
> stuff = calculate_stuff()
> if stuff < 0.5:
> break
> 
> quickly, to avoid the pain!
> 
> It may be too late though - even the
> above sanitised version is still too
> tightly coupled - how must
> calculate_stuff know where to find
> the inputs for its calculation?
> 
> You are gonna bleed!
> 
> :-)
> 
Indeed I fear Mr. Brady must expect a visit from the PSU. This highly
secretive organization is known to attack anyone who
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: urllib2.HTTPError: HTTP Error 204: NoContent

2008-10-19 Thread Philip Semanchuk


On Oct 19, 2008, at 6:13 AM, silk.odyssey wrote:


I am getting the following error trying to download an html page using
urllib2.

urllib2.HTTPError: HTTP Error 204: NoContent

The url is of this type:

http://www.amazon.com/gp/offer-listing/B000KJX3A0%3FSubscriptionId%3D183VXJS74KNQ89D0NRR2%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000KJX3A0

I can open it in my browser without problems.Any ideas on a solution?


Are you changing the user-agent? Some sites sniff user agents and  
return different results to browsers than to suspected bots.


I'd try it from here if you post a self-contained sample that  
demonstrates the problem. Should only take a couple of lines.




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


Re: Help with Iteration

2008-10-19 Thread Eric Wertman
>> Aaron Brady  wrote:
>>
>>> while 1:
>>>calculate_stuff( )
>>>if stuff < 0.5:
>>>break
>>
>> The thought police will come and get you.

Based on Aaron's previous posting history,  I suspect this was a joke.
--
http://mail.python.org/mailman/listinfo/python-list


Paramiko, termios - interactive shell connection.

2008-10-19 Thread Pawel Gega

Hi,

I am coding a small SSH client, I ve got some issues with creating 
pseudo terminal on server side, or at least I suppose that's the problem.

That is the 'ps auxf' run on SSH server:

   root  4317  0.0  0.3  33744   876 ?Ss   11:36   0:00
   /usr/sbin/sshd
   *### **4525** is the proper connection done with standard ssh
   client   *|
   root  4525  0.3  1.1  53036  2896 ?Ss   11:37   0:00  \_
   sshd: [EMAIL PROTECTED]/0**
   root  4532  0.0  0.8  15700  2060 pts/0Ss   11:37   0:00 
   |   \_ -bash
   root  4987  0.0  0.4  12596  1024 pts/0R+   11:38   0:00 
   |   \_ ps auxf  
   *### ..and 4733 is the connection made with my python script , as

   you can see it is not using PTS *
   root  4733  0.0  1.0  52940  2676 ?Ss   11:37   0:00  \_
   sshd: pgega [priv]
   pgega 4741  0.0  0.6  52940  1600 ?S11:37   0:00 
   |   \_ sshd: pgega

   root  4745  0.0  0.9  33768  2252 ?Ss   11:37   0:00  \_
   sshd: [accepted]

Do you see anything worng with my script ? Here is the source code:

Regards,
Pawel Gega

   ##

   #! /usr/bin/env python

   import paramiko
   import termios
   import sys
   import tty

   hostname = 'h1m'
   port = 22
   username = 'pgega'
   password = 'xxx'
   known_hosts = '/home/pgega/.ssh/known_hosts'

   def shell(chan):
   import select

   oldtty = termios.tcgetattr(sys.stdin)
   try:
   tty.setraw(sys.stdin.fileno())
   tty.setcbreak(sys.stdin.fileno())
   chan.settimeout(0.0)

   while True:
   r, w, e = select.select([chan, sys.stdin], [], [])
   if chan in r:
   try:
   x = chan.recv(1024)
   if len(x) == 0:
   print '\r\n*** EOF\r\n',
   break
   sys.stdout.write(x)
   sys.stdout.flush()
   except socket.timeout:
   pass
   if sys.stdin in r:
   x = sys.stdin.read(1)
   if len(x) == 0:
   break
   chan.send(x)

   finally:
   termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)

   if __name__ == '__main__':
   paramiko.util.log_to_file('psshc-interactive_shell.log')
   trn = paramiko.Transport((hostname,port))
   trn.connect(username=username, password=password)
   chn = trn.open_channel(kind='direct-tcpip',
   dest_addr=('h1m',22), src_addr=('hm',22))
   shell(chn)
   chn. close()

   ##



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


Re: Linux.com: Python 3 makes a big break

2008-10-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote:
>On 19 Oct 2008 07:44:52 -0700
>[EMAIL PROTECTED] (Aahz) wrote:
>>>   sys.stdout.write \
>>>  (
>> 
>> Why are you using a backslash?
>
>Because he hasn't opened the paren yet.  He could have put the open
>paren on the same line as the write obviating the need for the
>backslash but then his open/close parens wouldn't line up.  It just a
>matter of style.

Well, no, it's not *just* a matter of style.  I'm strongly opposed to
backslashes because they break when you get whitespace after them.  (And
note carefully that I said "when" and not "if".)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


python-list@python.org

2008-10-19 Thread Larry Bird
http://militarybodyarmor.blogspot.com/2008/10/law-enforcement-certifications.html
- Here it is don't miss out!
--
http://mail.python.org/mailman/listinfo/python-list


The truth about Prophet Muhammad (Peace Be Upon Him)

2008-10-19 Thread hi
The truth about Prophet Muhammad (Peace Be Upon Him)



Loving him is following him

Muslims all over the world are deeply hurt by the recent caricatures
of our beloved Prophet Muhammad , in Danish and several other
publications.

Every now and then, some Western media outlets provoke Muslims by
insulting the Prophet Muhammad . The baiting often succeeds in
eliciting Muslims' outrage and sporadic violence.

The latest incident started with a Danish newspaper's caricature
portraying the Prophet Muhammad as a terrorist. To add insult to
injury, Norwegian, French, German, Dutch and a few other newspapers
reprinted the defamatory cartoons to "defend"—they claimed—the freedom
of expression.

The real issue is not the freedom of expression. Free speech is not
and was never meant to be absolute. There are laws in the West that
ban certain kinds of speech, including those that incite anti-
Semitism, racism and violence. Moreover, some countries have laws
against blasphemy and defamation. To Muslims, banning blasphemy
against Allah and the Prophet Muhammad has a higher priority.

For the European newspapers to reprint the offensive cartoons to show
solidarity with their Danish counterpart seems akin to the plot the
leaders of Quraysh had hatched to assassinate Prophet Muhammad .

The Quraysh masterminds had figured that including representatives
from major tribes of Makkah in the heinous plot would make it
impossible for the Prophet's clan, Banu Hashim, to avenge. But Allah
willed that the Prophet Muhammad would migrate to Madinah unscathed
while the plotters laid siege to his house.

The West often underestimates the Muslims' reverence for their beloved
Prophet Muhammad, (sallallallahu alayhi wa sallam) and is, therefore,
staltred by the fierce Islamic reaction to an insult against him. Few
in the West know that for Muslims, loving their Prophet more than
themselves is a matter of faith, not choice.

Further, the depiction of the Prophet Muhammad , as a terrorist is a
falsification of history. He was considered "Al-Ameen," the
trustworthy, by his people even before he received the Prophethood.

Once, when asked by some of his followers to invoke Allah's wrath on
the enemies, he refused saying he had been sent as a mercy unto
mankind.

Objective Western intellectuals have acknowledged the superior
character of Prophet Muhammad . In his “The 100, a Ranking of the Most
Influential Persons in History," Michael H. Hart ranked Prophet
Muhammad, (sallallallahu alayhi wa sallam) No. 1 because "He was the
only man in history who was supremely successful on both the religious
and secular levels.”

Alphonse de Lamartine, a renowned 19th Century French writer, had this
to say about the Prophet Muhammad : "As regards all standards by which
human greatness may be measured, we may well ask, is there any man
greater than him?”

Unfortunately, some Muslims forget that loving their Prophet Muhammad
(Peace be upon him) means following him. Burning Danish embassies, as
they did in Damascus and Beirut, to avenge the insult to the Prophet
Muhammad is a complete disservice to him. Our violent reaction only
plays into the hands of those who wish to reinforce the negative
stereotypes about Muslims.

Do Muslims need reminding that Prophet Muhammad , forgave the people
of Ta'if who had rejected his message of monotheism and pelted him
with stones, bloodying him? Islamic tradition has it that when Jibreel
(Archangel Gabriel) sought his permission to punish the perpetrators,
the Prophet , instead prayed that some day the inhabitants of Ta'if
would leave their idols and worship Allah alone. Within a few years
they did.

Prophet Muhammad's, (sallallallahu alayhi wa sallam) servant once
noted his forgiving disposition, said, "I served the Prophet , for ten
years, and he never said ‘uf’ (a word indicating impatience or
discontent) to me and never blamed me by saying, `Why did you do so or
why didn't you do so?" (Al-Bukhari and Muslim)

Prophet Muhammad's, (sallallallahu alayhi wa sallam) archenemies hated
his Message and hurled malicious insults at him, to which he responded
with forbearance. Years later when he, sallallallahu alayhi wa sallam
returned as victor to Makkah, his city of birth which he was forced to
leave, he asked its awed citizens, "What do you think I'm going to do
to you." They said, "You are a noble brother, son of a noble brother;
we expect only good from you." The Prophet responded with a general
amnesty.

Let Muslims not forget that the Prophet , encouraged freedom of
expression. In the Battle of Badr, he changed the battlefield against
his own opinion due to the passionate advice of some young soldiers.

Part of the West's success today is the freedom of expression, of
thought, of religion—that draws Muslims to it from their oppressed
societies. For that, Muslims should be thankful to the West. After
all, freedom is an Islamic value that the West has embraced while
Muslim societies have forsaken.

Defending Prophet Muhammad

Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Eric Wertman
>> I (again) wonder what's the perfect way to store, OS-independent,
>> filepaths ?

I'm in agreement that perfect probably isn't applicable.  If I were
doing this myself, I might store the information in a tuple:

base = 'some root structure ('/' or 'C')
path = ['some','set','of','path','names']
filename = 'somefile.ext'

pathdata = (root,path,filename)

and write a couple of simple functions to reconstruct them based on the os.
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDE Question

2008-10-19 Thread Jorgen Grahn
On Sat, 18 Oct 2008 19:17:35 -0300, Fabio Zadrozny <[EMAIL PROTECTED]> wrote:
[I wrote]
>> (As a side note: I don't use Eclipse myself, but I have seen novice
>> programmers editing Python code with it, and what saw wasn't
>> impressive. They *did* some kind of Python "plugin" installed, but
>> were sitting there pressing SPACE to indent every line manually.)
>
> Not sure which plugin they had, but I'm pretty positive that if they
> had Pydev installed they'd have auto-indent without any problems (I
> can assure you that auto-indent is a feature that received a lot of
> attention in Pydev).

Ok, then it wasn't Pydev, or a very old or misconfigured one. I didn't
know at that time whether there was decent support for Python in
Eclipse or not, so I decided whatever the problem was, it was their
problem :-)

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: better scheduler with correct sleep times

2008-10-19 Thread Scott David Daniels

Scott David Daniels wrote:

def time_server(commands):
'''Process all scheduled operations that arrive on queue commands'''
...

queue = Queue.Queue()
thread.thread.start_new_thread(queue)

> queue.put((time.time() + dt, callable, args, {}))
> ...

And of course of the three lines that were not cut and pasted, one
was mis-transcribed.
It should have read:
thread.start_new_thread(time_server, (queue,))

Sheepishly,
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


regexp in Python (from Perl)

2008-10-19 Thread Pat
I have a regexp in Perl that converts the last digit of an ip address to 
 '9'.  This is a very particular case so I don't want to go off on a 
tangent of IP octets.


 ( my $s = $str ) =~ s/((\d+\.){3})\d+/${1}9/ ;

While I can do this in Python which accomplishes the same thing:

ip = ip[ :-1 ]
ip =+ '9'

I'm more interested, for my own edification in non-trivial cases, in how 
one would convert the Perl RE to a Python RE that use groups.  I am 
somewhat familiar using the group method from the re package but I 
wanted to know if there was a one-line solution.


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


Re: indentation

2008-10-19 Thread Jorgen Grahn
On 19 Oct 2008 14:34:45 GMT, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Sun, 19 Oct 2008 07:16:44 -0700, Gandalf wrote:
>
>> every time I switch editor all the script  indentation get mixed up, and
>> python start giving me indentation weird errors. indentation also  hard
>> to follow because it invisible  unlike brackets { }
...
>> is there any solution to this problems?
>
> Discipline. Choose a standard indent and stick to it.

Doesn't pretty much everyone use spaces and a four-position indent? I
don't think I've ever come across any half-decent Python code which
didn't follow that convention.

...
> Especially never mix tabs and spaces in the same file.

Actually, the only really likely reason he sees "mixed up" indentation
is that he has mixed TAB/space source code *and* a misconfigured[0]
editor which sets the TAB stops at anything else than every 8th
character.

If I was him, I'd check and fix my editors first, and/or tell my
coworkers to stop emitting broken[0] TABs.

/Jorgen

[0] This is an old and tedious topic ... my view on TABs is that they
are useless iff they aren't rendered the same way everywhere. The
size 8 is hard-coded into terminals, printers and programs since
ancient times; thus anything else is wrong.

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: inserting Unicode character in dictionary - Python

2008-10-19 Thread Martin v. Löwis
> Well, the if no encoding is declared, it (quite sensibly) assumes UTF-8,
> so for my purposes this boils down to using a UTF-8 editor -- which I
> always do anyway.  But do I still have to put a "u" before my string
> literals in order to have it treated as characters rather than bytes?

Yes.

> I'm hoping that the answer is "no"

Then you need to switch to Python 3.0, when it comes out. Its string
literals denote unicode strings.

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


Re: xor: how come so slow?

2008-10-19 Thread Aaron Brady
Steven D'Aprano wrote:

> On Sun, 19 Oct 2008 04:38:04 +, Tim Roberts wrote:
>
>> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>>>
>>>On Fri, 17 Oct 2008 20:51:37 +1300, Lawrence D'Oliveiro wrote:
>>>
 Is piece really meant to be random? If so, your create_random_block
 function isn't achieving much--xoring random data together isn't going
 to produce anything more exciting than less random data than you
 started with.
>>>
>>>Hmmm... why do you say that xoring random data with other random data
>>>produces less randomness than you started with?
>>>
>>>I'm not saying that you're wrong, and certainly it is pointless since
>>>you're not going to improve on the randomness of /dev/urandom without a
>>>lot of work. But less random?
>> 
>> For those who got a bit lost here, I'd would point out that Knuth[1] has
>> an excellent chapter on random numbers that includes a detailed
>> discussion of this effect.  His net takeaway is that most of the things
>> people do to increase randomness actually have exactly the opposite
>> effect.
>
> I don't doubt it at all. But xoring random data with more random data? 
> I'm guessing that if the two sources of data are independent and from the 
> same distribution, then xoring them is pointless but not harmful. Here's 
> a rough-and-ready test which suggests there's little harm in it:
>
>
 import os, math
 def rand_data(size):
> ... return [ord(c) for c in os.urandom(size)]
> ...
 def mean(data):
> ... return sum(data)/len(data)
> ...
 def stdev(data):
> ... return math.sqrt( mean([x**2 for x in data]) - mean(data)**2 )
> ...
 A = rand_data(1000)  # good random data
 B = rand_data(1000)  # more good random data
 AB = [a^b for (a,b) in zip(A, B)]  # is this still good random data?
 assert len(AB) == len(A) == len(B)

 mean(A), stdev(A)
> (126, 73.91887445030531)
 mean(B), stdev(B)
> (128, 74.242844773082339)
 mean(AB), stdev(AB)
> (129, 74.39085965358916)
>
>
> Note: I wouldn't take the above terribly seriously. Mean and standard 
> deviation alone are terrible measures of the randomness of data. But this 
> does suggest that any deviation from uniform randomness will be quite 
> subtle.
>
>
>

Operations like 'and' and 'or' will tend to destroy randomness.  'and'
tends to the 0-string and 'or' tends to the 1-string.  I feel like 'xor'
should be safe (like Steven), but is the proof merely the half-and-half
split of the truth table?

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


re.search over a list

2008-10-19 Thread Pat
While I can use a for loop looking for a match on a list, I was 
wondering if there was a one-liner way.


In particular, one of my RE's looks like this '^somestring$' so I can't 
just do this: re.search( '^somestring$', str( mylist ) )


I'm not smart enough (total newbie) to code up a generator expression 
and I was wondering if I'm missing something obvious.


I love succinct but clearly understandable code.

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


Re: regexp in Python (from Perl)

2008-10-19 Thread Bruno Desthuilliers

Pat a écrit :
I have a regexp in Perl that converts the last digit of an ip address to 
 '9'.  This is a very particular case so I don't want to go off on a 
tangent of IP octets.


 ( my $s = $str ) =~ s/((\d+\.){3})\d+/${1}9/ ;

While I can do this in Python which accomplishes the same thing:

ip = ip[ :-1 ]
ip =+ '9'


or:

ip = ip[:-1]+"9"


I'm more interested, for my own edification in non-trivial cases, in how 
one would convert the Perl RE to a Python RE that use groups.  I am 
somewhat familiar using the group method from the re package but I 
wanted to know if there was a one-line solution.


Is that what you want ?

>>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.1")
'192.168.1.9'


re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.100")

'192.168.1.9'


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


Re: indentation

2008-10-19 Thread Bruno Desthuilliers

Gandalf a écrit :

every time I switch editor all the script  indentation get mixed up,
and python start giving me indentation weird errors.
indentation also  hard to follow because it invisible  unlike brackets
{ }

is there any solution to this problems?


Properly configure your eidtors to use 4 spaces (not tabs) for intentation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Stef Mientki

Eric Wertman wrote:

I (again) wonder what's the perfect way to store, OS-independent,
filepaths ?
  


I'm in agreement that perfect probably isn't applicable.  If I were
doing this myself, I might store the information in a tuple:

base = 'some root structure ('/' or 'C')
path = ['some','set','of','path','names']
filename = 'somefile.ext'

pathdata = (root,path,filename)

and write a couple of simple functions to reconstruct them based on the os.
  

Eric, I like your idea.
It looks like a workable technique,
the user should initial define the roots once and everything works.
It should even work for network drives and websites.

Duncan, in windows it's begin to become less common to store settings in 
Docs&Settings,
because these directories are destroyed by roaming profiles (a big 
reason why I can't run Picassa ;-(
It's more common to follow the portable apps approach, store them in the 
application directory.


Drobinow, I want to distribute an application with a large number of 
docs and examples.
Now for this application I can put everything in subpaths of the 
main-application,
but you triggered me to put a warning in my code if I go outside the 
application path.

Another application I've in mind, is a data manager (now written in Delpi),
in which I organize all my information: docs, websites, measurement data 
etc.


Others, thank you for the ideas, you learende me some new os.path functions.

cheers,
Stef


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


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


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Aaron Brady
Duncan Booth wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>
>> In Linux, config files should go into:
>> 
>> ~/./ or /etc//
>> 
>> In Windows (which versions?) then should go into the Documents And 
>> Settings folder, where ever that is.
>> 
>> There's no single string which can represent both of these conventions!
>
> The first of those should do nicely for both Linux and Windows:
>
 os.path.normpath(os.path.expanduser('~/.appname'))
> 'C:\\Documents and Settings\\Duncan\\.appname'

A tuple of path elements, I would think.

>>> a= ( 'c:', 'windows', 'system' )
>>> a= ( '~', 'usr', 'bin' )
>>> a= ( '..', 'src' )

You'll want a subclass too, which has a file for the last name, instead 
of just folders.

>>> a= ( 'c:', 'python', 'python.exe' )

If '..' and '~' aren't universally, recognized, you'll want special
flags.

>>> DirUp= type( 'DirUp', (object,), { '__repr__': ( lambda self: 'DirUp' ) } 
>>> )()
>>> a= ( DirUp, 'src' )
>>> a
(DirUp, 'src')

As for rendering them, 'win', 'unix', and 'mac' could be methods.


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


Re: re.search over a list

2008-10-19 Thread Bruno Desthuilliers

Pat a écrit :
While I can use a for loop looking for a match on a list, I was 
wondering if there was a one-liner way.


In particular, one of my RE's looks like this '^somestring$' so I can't 
just do this: re.search( '^somestring$', str( mylist ) )


I'm not smart enough (total newbie) to code up a generator expression 
and I was wondering if I'm missing something obvious.


words = ['foo', 'bar', 'somestring', 'baaz']
re.search(r"^somestring$", "\n".join(words), re.MULTILINE)



I love succinct but clearly understandable code.


separator.join(sequence_of_strings) is a very common python idiom, so 
you can consider it as readable.


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


Re: indentation

2008-10-19 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

(snip)

You can use tabs, or spaces. If you use spaces, you can choose 4 spaces, 
or 8, or any number,


By all means, make it 4 spaces - that's the standard.

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


Re: Help with Iteration

2008-10-19 Thread Aaron Brady
Hendrik van Rooyen wrote:

> Aaron Brady  wrote:
>
>>while 1:
>>calculate_stuff( )
>>if stuff < 0.5:
>>break
>
> The thought police will come and get you.
>
> You are doing things by "side effect"!
> You are using a global called "stuff"!
> You are relying on an implementation
> detail!
>
> While their cudgels are bouncing off
> your skull, they will scream the above three
> lines into your swiftly swelling ears!

My manager doesn't know a thing about programming, and in fact he
failed the intro to critical thinking course at his college. He's
scared of truth tables. He's bored and picks fights. He spent my bonus
on a new VGA monitor for his second office. When I want to change my
syntax colors, he has to get permission from his bartender. He is
living proof that knowledge is not power. I'm impractically idealistic.
I have abstractions to reuse code if aliens abduct us. (They are
UFO_String and NonUFO_String.) I have macros for the number 1, because
'one' is easier to read. Some of my code has an accessor
method for the number 1, one(), just in case its value changes. We're
going to fire each other. In other news, I don't really have one.

If customers are stupid, should you sell stupid software?


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


Re: better scheduler with correct sleep times

2008-10-19 Thread sokol

> from circuits.core import Manager, Component, Event, listener
> from circuits.timers import Timer

what is circuits?
--
http://mail.python.org/mailman/listinfo/python-list


Re: indentation

2008-10-19 Thread Derek Martin
On Sun, Oct 19, 2008 at 06:05:08PM +, Jorgen Grahn wrote:
> Doesn't pretty much everyone use spaces and a four-position indent? 

I can't speak for everyone, or even "pretty much everyone"... but I
know of several people who favor the idea of "indent with tab, align
with space."  The advantage to this scheme is that anyone using a
half-sane editor can very easily change the level of indentation to
their preference, meanwhile keeping the rest of the code aligned
properly (though this may well interfere with keeping line lengths to
80 columns, or some other decided-upon number).  I favor this myself
actually, though I rarely use it for Python code I write, because that
almost invariably needs to work with someone else's code who insists
on the "standard" you mentioned.  

I know plenty of people who prefer a full 8-column indent, feeling that
it makes indentations (and therefore the logical blocks wich the
indentation is meant to indicate) much clearer, though most of them
are primarily C coders.  Some switch to 4 for python, and some prefer
to keep 8 for pretty much everything they write.

> I don't think I've ever come across any half-decent Python code
> which didn't follow that convention.

I have. :) Unless one defines a lack of tabs as a criteria of
"half-decent Python code" -- which I obviously don't.

> [0] This is an old and tedious topic ... 

This is very true... though clearly to anyone who hasn't encountered
it before, it is rather new.

> my view on TABs is that they are useless iff they aren't
> rendered the same way everywhere. The size 8 is hard-coded into
> terminals, printers and programs since ancient times; thus
> anything else is wrong.

This, on the other hand, is quite false -- not your opinion, perhaps,
but all of the facts you've put forth in support of it.  The tab size
of nearly every tty device I've interacted with in the last 25 years
*defaulted* to 8, but is configurable using any of various terminal
control programs, such as tabs, stty, etc. (though I wouldn't know how
to do this on Windows, or if it's even possible/relevant)...  The
utility of adjustable tabs is what I already stated above.  I'm not
saying you should change it... just that it is very much *not*
hard-coded.  In fact, most of the terminal devices I've used let you
set arbitrary tab stops at whatever column positions you like.
Occasionally useful, though not to me personally.

One thing is for sure: it's essential that whatever formatting you
decide to use, everyone touching that code needs to use the same one,
or else the result is an annoying mess.  Vim (and quite probably other
editors) solves this by providing a way to set the options in the file
you're editing, which is one of many reasons why I favor it over
anything else.  For example, at the top of your file:

  #!/usr/bin/python
  # vim:ts=4:sw=4:expandtab

Though of course, using this kind of mechanism quickly becomes gross
if everyone is using a different editor, and they all support a
similar but different mechanism for doing so.



-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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


Re: better scheduler with correct sleep times

2008-10-19 Thread sokol
On Oct 19, 6:25 pm, Scott David Daniels <[EMAIL PROTECTED]> wrote:
> qvx wrote:
> > I need a scheduler which can delay execution of a
> > function for certain period of time.
> > My attempt was something like this:  ... <<>>
> > Is there a better way or some library that does that?
>
> The trick is to use Queue's timeout argument to interrupt your sleep
> when new requests come in.
>
> def time_server(commands):
>      '''Process all scheduled operations that arrive on queue commands'''
>      pending = []
>      while True:
>          now = time.time()
>          while pending and pending[0][0] <= now:
>              when, function, args, kwargs = heapq.heappop(pending)
>              function(*args, **kwargs)
>          try:
>              command = commands.get(timeout=pending[0][0] - now
>                                             if pending else None)
>          except Queue.Empty:
>              pass
>          else:
>              if command is None:
>                  break
>              heapq.heappush(pending, command)
>
> queue = Queue.Queue()
> thread.thread.start_new_thread(queue)
> queue.put((time.time() + dt, callable, args, {}))

I see what you did there. You are keeping the queue empty
so you get notified for free, while I introduced a new
threading Condition to detect insertions.
All that is missing in your version is to put back all
pending tasks when somebody sends the stop (None) request.

Shouldn't sched module do something similar?

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


Re: indentation

2008-10-19 Thread bearophileHUGS
Derek Martin:
> I know of several people who favor the idea of "indent with tab, align
> with space." [...] I favor this myself actually, [...]

Thanks Guido, in Python3 this is finally a Syntax Error (I have asked
for this probably about three years ago).

Unfortunately the new Python-syntax-based Delight language starts with
a half-bad foot regarding indents:
http://delight.sourceforge.net/syntax.html

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


Re: indentation

2008-10-19 Thread Ben Finney
Gandalf <[EMAIL PROTECTED]> writes:

> every time I switch editor all the script  indentation get mixed up,
> and python start giving me indentation weird errors.
> indentation also  hard to follow because it invisible  unlike brackets
> { }
> 
> is there any solution to this problems?

Follow PEP 8 http://www.python.org/dev/peps/pep-0008> for all
code you write.

Follow whatever convention exists in all code you edit.

Agitate for consensus if you edit code which is inconsistent.

-- 
 \ “Geeks like to think that they can ignore politics. You can |
  `\leave politics alone, but politics won't leave you alone.” |
_o__)—Richard Stallman, 2002-07-26 |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread infixum
On Oct 19, 12:51 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
> Lawrence D'Oliveiro wrote:
> > In message <[EMAIL PROTECTED]>, Dotan
> > Cohen wrote:
>
> >> I often see mention of SMBs that either want to upgrade their Windows
> >> installations, or move to Linux, but cannot because of inhouse VB
> >> apps.
>
> > Probably best to leave those legacy VB apps alone and develop new
> > replacements in a more open, cross-platform language, like Python.
>
> Sorry but for GUI design, Python is pre-historic ;-)
> Stef

Some folks below mention wxPython, which (I think) works pretty
decently.

Another option is IronPython, the dot net based version of Python.
Much of it runs under Mono on Linux.  The dot Net Windows and controls
look decent in both environments (Windows and Linux), and aren't that
difficult to code.

IronPython has a mailing list; you might want to cross-post there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: indentation

2008-10-19 Thread Jorgen Grahn
On Sun, 19 Oct 2008 15:50:59 -0400, Derek Martin <[EMAIL PROTECTED]> wrote:

> On Sun, Oct 19, 2008 at 06:05:08PM +, Jorgen Grahn wrote:
>> Doesn't pretty much everyone use spaces and a four-position indent? 
>
> I can't speak for everyone, or even "pretty much everyone"... but I
> know of several people who favor the idea of "indent with tab, align
> with space."  The advantage to this scheme is that anyone using a
> half-sane editor can very easily change the level of indentation to
> their preference, meanwhile keeping the rest of the code aligned
> properly (though this may well interfere with keeping line lengths to
> 80 columns, or some other decided-upon number). 

I'm happy to say I have never seen the kind of code you mention. If I
understand you correctly, if you sent me code to look at, I would
either have to change the TAB setting of all relevant tools to
four-spaced TABs (remembering to restore them afterwards), or suffer
looking at the code eight-indented -- twice the one I'm used to.

> I favor this myself
> actually, though I rarely use it for Python code I write, because that
> almost invariably needs to work with someone else's code who insists
> on the "standard" you mentioned.

Yes; what you do makes sense in a way, but it seems very incompatible
with what most people do.

What has made me dread alternate TAB settings is not the style you
describe, but the uncontrolled one where some lines are indented with
oddly-sized TABs and others (partly) with spaces. When trying to read
such code, it's not uncommon that you have to try several different
TAB sizes before you hit the one where the code stops looking like
gibberish. And often you don't find one, because someone beat you to
it and the code now uses several different TAB settings in different
parts of the file ... At least if it's Python code, chances are good
that it refuses to load such code, or that it crashes soon.

...
>> [0] This is an old and tedious topic ... 
>
> This is very true... though clearly to anyone who hasn't encountered
> it before, it is rather new.
>
>> my view on TABs is that they are useless iff they aren't
>> rendered the same way everywhere. The size 8 is hard-coded into
>> terminals, printers and programs since ancient times; thus
>> anything else is wrong.
>
> This, on the other hand, is quite false -- not your opinion, perhaps,
> but all of the facts you've put forth in support of it.  The tab size
> of nearly every tty device I've interacted with in the last 25 years
> *defaulted* to 8, but is configurable using any of various terminal
> control programs, such as tabs, stty, etc. (though I wouldn't know how
> to do this on Windows, or if it's even possible/relevant)...

Ok, I stand corrected. I shouldn't have brought it up, because the
defaults are what matters. Since text files contain no metainformation
about what TAB size they use, you have no chance to reconfigure your
tools for every text file they process.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: indentation

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 19:03:29 +0200, Bruno Desthuilliers wrote:

> Steven D'Aprano a écrit :
> 
> (snip)
> 
>> You can use tabs, or spaces. If you use spaces, you can choose 4
>> spaces, or 8, or any number,
> 
> By all means, make it 4 spaces - that's the standard.

It's *a* standard. I believe it is the standard for the Python standard 
library, but there are other standards.


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


Re: better scheduler with correct sleep times

2008-10-19 Thread Scott David Daniels

sokol wrote:

...

I see what you did there. You are keeping the queue empty
so you get notified for free, while I introduced a new
threading Condition to detect insertions.
All that is missing in your version is to put back all
pending tasks when somebody sends the stop (None) request.

Shouldn't sched module do something similar?


Probably so, I was just scratching an itch that I had.
My target was to make the decisions as clear as possible.
What I started from is "you only need to do work when
the next thing comes up or another entry is added."

That was the core I was going after, and I just had the None
in there so my tests could stop gracefully (in fact I printed
the leftover queue when I was testing).

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: better scheduler with correct sleep times

2008-10-19 Thread James Mills
On Mon, Oct 20, 2008 at 5:31 AM, sokol <[EMAIL PROTECTED]> wrote:
>
>> from circuits.core import Manager, Component, Event, listener
>> from circuits.timers import Timer
>
> what is circuits?

If you're interested:

An event framework with a focus on Component architectures.
It can be downloaded currently via Mercurial at:
http://hg.softcircuit.com.au/circuits/
or
http://freehg.org/u/prologic/circuits/

Website coming soon at: http://trac.softcircuit.com.au/circuits/
1.0 Release also coming soon...

cheers
James

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


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 15:40:32 +, Duncan Booth wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> 
>> In Linux, config files should go into:
>> 
>> ~/./ or /etc//
>> 
>> In Windows (which versions?) then should go into the Documents And
>> Settings folder, where ever that is.
>> 
>> There's no single string which can represent both of these conventions!
> 
> The first of those should do nicely for both Linux and Windows:
> 
 os.path.normpath(os.path.expanduser('~/.appname'))
> 'C:\\Documents and Settings\\Duncan\\.appname'


Except Windows users will be wondering why they have a directory starting 
with '.' in their home directory. Dot to make files hidden is not AFAIK 
supported by Windows.



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


Re: What's the perfect (OS independent) way of storing filepaths ?

2008-10-19 Thread Steven D'Aprano
On Sun, 19 Oct 2008 20:50:46 +0200, Stef Mientki wrote:

> Duncan, in windows it's begin to become less common to store settings in
> Docs&Settings,
> because these directories are destroyed by roaming profiles 

Isn't *everything* destroyed by roaming profiles? *wink*

Seriously, I don't know anyone who has anything nice to say about roaming 
profiles.


> (a big
> reason why I can't run Picassa ;-(
> It's more common to follow the portable apps approach, store them in the
> application directory.

User config files in a global directory? That bites.


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


Re: regexp in Python (from Perl)

2008-10-19 Thread MRAB
On Oct 19, 5:47 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Pat a écrit :
>
> > I have a regexp in Perl that converts the last digit of an ip address to
> >  '9'.  This is a very particular case so I don't want to go off on a
> > tangent of IP octets.
>
> >  ( my $s = $str ) =~ s/((\d+\.){3})\d+/${1}9/ ;
>
> > While I can do this in Python which accomplishes the same thing:
>
> > ip = ip[ :-1 ]
> > ip =+ '9'
>
> or:
>
> ip = ip[:-1]+"9"
>
> > I'm more interested, for my own edification in non-trivial cases, in how
> > one would convert the Perl RE to a Python RE that use groups.  I am
> > somewhat familiar using the group method from the re package but I
> > wanted to know if there was a one-line solution.
>
> Is that what you want ?
>
>  >>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.1")
> '192.168.1.9'
>
> >>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.100")
>
> '192.168.1.9'

The regular expression changes the last sequence of digits to
"9" ("192.168.1.100" => "192.168.1.9") but the other code replaces the
last digit ("192.168.1.100" => "192.168.1.109").
--
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2.HTTPError: HTTP Error 204: NoContent

2008-10-19 Thread Mark Sapiro
On Oct 19, 9:49 am, Philip Semanchuk <[EMAIL PROTECTED]> wrote:
> On Oct 19, 2008, at 6:13 AM, silk.odyssey wrote:
>
> > I am getting the following error trying to download an html page using
> > urllib2.
>
> > urllib2.HTTPError: HTTP Error 204: NoContent
>
> > The url is of this type:
>
> >http://www.amazon.com/gp/offer-listing/B000KJX3A0%3FSubscriptionId%3D...
>
> > I can open it in my browser without problems.Any ideas on a solution?
>
> Are you changing the user-agent? Some sites sniff user agents and  
> return different results to browsers than to suspected bots.


I tried it.

>>> import urllib2
>>> url = 
>>> 'http://www.amazon.com/gp/offer-listing/B000KJX3A0%3FSubscriptionId%3D183VXJS74KNQ89D0NRR2%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000KJX3A0'
>>> op = urllib2.urlopen(url)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "/usr/lib/python2.5/urllib2.py", line 380, in open
response = meth(req, response)
  File "/usr/lib/python2.5/urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.5/urllib2.py", line 418, in error
return self._call_chain(*args)
  File "/usr/lib/python2.5/urllib2.py", line 353, in _call_chain
result = func(*args)
  File "/usr/lib/python2.5/urllib2.py", line 499, in
http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 204: NoContent
>>> headers = {}
>>> headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; 
>>> rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
>>> ro = urllib2.Request(url, None, headers)
>>> op = urllib2.urlopen(ro)
>>> page = op.read()
>>> page
 (lots of HTML)

So the answer is as Philip suggests - amazon.com doesn't like 'Python-
urllib/2.5' as a User-Agent. You have to give it something that looks
like a browser.

--
(for email use this address please - you can figure it out)

Mark Sapiro mark at msapiro net   Any clod can have the facts;
San Francisco Bay Area, Californiahaving opinions is an art. -
  C. McCabe, The Fearless
Spectator
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread bearophileHUGS
Stef Mientki:
> it's just Object Pascal , which is inferior to Python.

They are quite different languages, you can't compare them in a simple
way.
Delphi is statically typed, and compiles very quickly producing
"small" exes; "algorithmic" code can run a hundred times faster than
Python code. There are lot of people still that think that a
statically typed language is safer.
Delphi is kinda old, so today there are better languages than Delphi
(like D), but when Delphi 2-3 was out, there weren't many other
languages with IDEs at its level, especially for programs with a nice
GUIs plus interfaces with DBMSs. Today you can write programs with
FreePascal, that is free. Bashing other languages doesn't make Python
any better.

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


Re: regexp in Python (from Perl)

2008-10-19 Thread bearophileHUGS
MRAB:
> The regular expression changes the last sequence of digits to
> "9" ("192.168.1.100" => "192.168.1.9") but the other code replaces the
> last digit ("192.168.1.100" => "192.168.1.109").

Uhmm, this is a possible alternative:

>>> s = " 192.168.1.100 "
>>> ".".join(s.strip().split(".")[:3]) + ".9"
'192.168.1.9'

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


Re: keyword in package name.

2008-10-19 Thread Christian Heimes

Marc 'BlackJack' Rintsch wrote:
`com_spam.app1`!?  I would even recommend this with domains that don't 
clash with keywords because if several people start to use this package 
name convention you will get name clashes at package level.  Say there 
are two vendors with a `com` TLD, how do you install their packages?  
Into the same `com/` subdirectory?  The `__init__.py` of which vendor 
should live at the `com/` directory level?  If you install them into two 
different directories but want to import modules from both vendors -- how?


It's possible with name space packages but every vendor must define the 
com package as a name space package w/o putting any code into the 
__init__.py except the name space declaration.


Christian

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


Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread david . lyon

Quoting [EMAIL PROTECTED]:


Stef Mientki:

it's just Object Pascal , which is inferior to Python.


They are quite different languages, you can't compare them in a simple
way.
Delphi is kinda old, so today there are better languages than Delphi
(like D), but when Delphi 2-3 was out, there weren't many other
languages with IDEs at its level, especially for programs with a nice
GUIs plus interfaces with DBMSs.


I have programmed Delphi for years.. and was pretty much forced to  
move to python for different reasons.


I would go along best with the description of delphi being "old". It  
was great in its time... and had many advancements over others. Still  
has some things that I would dearly love in python... like "skinned"  
gui applications.


As for porting... don't.

Just rewrite them

Shouldn't be so hard...

David






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


Re: Linux.com: Python 3 makes a big break

2008-10-19 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Dennis Lee
Bieber wrote:

> There is also the matter that the original material is using " on
> each line to delimit the string, and then \" within the line to escape
> the desired output "s, rather than either using ' for the string and
> bare " for the output characters ...

I prefer using double-quotes universally. One less decision to make.

> ... or triple quoting the whole block... 

Not a good idea.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linux.com: Python 3 makes a big break

2008-10-19 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Aahz wrote:

> I'm strongly opposed to backslashes because they break when you get
> whitespace after them.

1) I've never had that problem.
2) Even if I did, it would report a syntax error, it's not going to fail
silently and introduce any run-time bugs, is it?
--
http://mail.python.org/mailman/listinfo/python-list


Re: keyword in package name.

2008-10-19 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>,
Abhishek Mishra wrote:

> I have the habit of using domain names (of either the application or
> company) in reverse in package names.
> 
> for e.g. com.spam.app1
> 
> I've recently started a project for an indian domain (tld = .in),
> which leads to a package name like
> 
> in.spam.app1
> 
> This causes a syntax error, as "in" is a keyword.

The problem is that domain names aren't obliged to conform to any
programming language syntax. So using them directly in identifiers is
asking for trouble anyway. Best to avoid it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: keyword in package name.

2008-10-19 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Steve
Holden wrote:

> Though I do think it's an inappropriate choice for Python.

I'd characterize it as a Javaism. It exemplifies the difference between the
corporate, management-driven Java development model, versus the more
freewheeling, informal Python one. Like the difference between strict
subclassing and duck-typing.
--
http://mail.python.org/mailman/listinfo/python-list


Re: xor: how come so slow?

2008-10-19 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Steven D'Aprano
> wrote:
> 
>> On Sat, 18 Oct 2008 09:16:11 +1300, Lawrence D'Oliveiro wrote:
>> 
>>> Data can come in fractional bits. That's how compression works.
>> 
>> If you don't believe me, try compressing a single bit and see if you get
>> a "fractional bit".
> 
> If both states of the bit are not equally likely, then you do indeed have
> a fractional bit, since
> 
> nrbits = (- logbase2(P[bit = 0]) - logbase2(P[bit = 1])) / 2

Oops, sorry, the formula should of course be

nrbits = - P[bit = 0] * logbase2(P[bit = 0])
- P[bit = 1] * logbase2(P[bit = 1])
--
http://mail.python.org/mailman/listinfo/python-list


Big money in a simple program!!!

2008-10-19 Thread [EMAIL PROTECTED]
IT'S SIMPLE AND IT'S LEGAL!!!
Who doesn’t want to make tons of money ridiculously easy? Read this
letter follow the instructions, and like me you’ll never have to worry
about
money again.
I was browsing through news groups just like you are right now and
Came across a article similar to this saying that you could make
thousands
Of dollars within weeks with only an initial investment of $12.00!! So
I
Thought yeah right. This must be a scam, but like most of us, I was
Curious, so I kept reading. Anyway it said that you send two dollars
to
Each of the six names and addresses stated in the article. You then
place
Your own name and address on the bottom of the list at number six and
post
The article to at least 200 newsgroups. (there are thousands) No
catch
That was it. So after talking to a few people and thinking it over I
Decided to give it a try. What have I got to lose except 6 stamps and
$12.00 right? Then I invested the measly twelve dollars. WELL GUESS
WHAT!!!
Within 7 days, I started getting money in the mail!!! I was shocked.
I
Thought it was going to stop but it just kept coming. In my first week
I
Made $50.00. By the end of the second week I had $1,800.00. In the end
of
The third week I made $10,000.00!!! It's still growing right now. This
is
Now my fourth week and I have made a total of just over $76,000.00!
and
It's still coming in rapidly. This is certainly worth $12.00 and 6
stamps.
I have spent more than that on the lottery!!
Let me tell you how this works and most importantly why it works.
Also
Make sure that you print a copy of this article NOW so you can get
the
Information off of it as you need it. I promise you that if you follow
the
Directions exactly, that you will start making more money than you
Possibly thought just by doing something so easy!! SUGGESTION: READ
THIS
ENTIRE MESSAGE CAREFULLY (Print it out or down load it) Follow the
simple
Directions and watch the money come in! It's easy. It's legal. And
your
Investment is only $12.00 (plus postage) IMPORTANT: This is not a rip
off;
It is not indecent; it is not illegal; and it is virtually no risk -
it
Really works! If all of the following instructions are adhered to,
you
Will receive extraordinary dividends. PLEASE NOTE: please follow
these
Directions exactly and $100,000 or more can be yours in 20 to 60
days.
This program remains successful because of the honesty and integrity
of
The participants. Please continue its success by carefully adhering to
the
Instructions. You will now become a part of the mail order business.
In
This business your product is not solid and tangible, it's a service.
You
Are in the business of developing a mailing list. Many large
corporations
Are happy to pay big bucks for quality list. However, the money made
from
The mailing list is secondary to the income, which is made from
people
Like you and me asking to be included to that list. Here are the four
Steps to success:
STEP 1: Get 6 separate pieces of paper write the following on each
piece
Of paper "PLEASE PUT ME ON YOUR MAILING LIST."
Now get 12 us 1dollar bills and place TWO bills inside EACH of the
six
Pieces of paper so the bills will not be seen through the envelope to
Prevent thievery. Next place one paper in each of the 6 envelopes and
seal
Them.
MAKE SURE THERE ARE ENOUGH STAMPS ON YOUR ENVELOPES. You should now
Have 6
Sealed envelopes, each with a piece of paper stating the above phrase
your
Name and address and two $1.00 bill. What you are doing is creating a
Service. THIS IS ABSOLUTELY LEGAL! You are requesting a legitimate
service
And you are paying for it! Like most of us, I was a little skeptical
and a
Little worried about the legal aspects of it all. So I checked it out
with
The U.S. Post Office (1-800-725-2161) and they confirmed that it is
indeed
Legal! Mail the six envelopes to the following addresses:
>>> >>#1) Jia Ming
>>> >> 2101 Cumberland Ave
>>> >> Apt 2105 West Lafayette IN 47906
___
>>> >>#2) Kimberly Williams
>>> >> 11865 S.W. 91st. Ave. #49
>>> >> Tigard OR. 97223
___
>>> >>#3) Rahim Karim
>>> >> 105 Hillpine Rd. Apt M-2
>>> >> Columbia SC 29212
___
>>> >>#4)Bruno Antonelli Jr.
>>> >> 8621 Euclid-Chardon Rd.
>>> >> Kirtland, OH 44094
___
>>> >>#5) Carrie Bowers
>>> >>> 403 New St
>>> >>> Fairport Harbor, OH 44077
___
>>> >> #6) Eric Anthony
>>>  1258 1/2 Spaulding AVE.
>>>  Los Angeles, CA 90019

STEP 2: Now take the #1 name off the list that you see above,
Move the other names up (6 becomes 5, 5 becomes 4, etc) and add YOUR
name
As number 6 on the list.
STEP 3: Change anything you need to but try to keep this article as

  1   2   >